C ++映射模板派生类

时间:2014-08-16 13:02:37

标签: c++

您好我有以下结构和数据类型:

enum EWorkerType
{
   WorkerType1,
   WorkerType2,
   LastWorker
};

template<class DerivedType>
struct CHandlerMethod
{
};

struct CFunctorA : public CHandlerMethod<CFunctorA>
{
};
struct CFunctorB : public CHandlerMethod<CFunctorB>
{
};

template<class TFunctor>
struct CWorkerHandler
{
    CHandlerMethod<TFunctor>* m_HandlerMethod;
};

typedef std::vector<CWorkerHandler<CFunctorA>*> WorkerA;
typedef std::vector<CWorkerHandler<CFunctorB>*> WorkerB;

我需要一个方向来在EWorkerType :: WorkerType1到WorkerA和EWorkerType :: WorkerType2到WorkerB之间创建一个const映射。

我尝试了这个方向

struct WorkersMapping
{
WorkersMapping()
{
    m_WorkersMapper.insert(EWorkerType::WorkerType2, CFunctorA::value_type());
}
static std::map<EWorkerType, ???> m_WorkersMapper;
};
static WorkersMapping m_WorkersMapping;

2 个答案:

答案 0 :(得分:2)

您可以使用(编译时):

template <EWorkerType> struct WorkersMapping;

template <> struct WorkersMapping<WorkerType1>
{
    using type = WorkerA;
};

template <> struct WorkersMapping<WorkerType2>
{
    using type = WorkerB;
};

或者是否正确选择了enum值,例如:

template <EWorkerType E> struct WorkersMapping
{
    using type = typename std::tuple_element<E, std::tuple<WorkerA, WorkerB>>::type;
};

答案 1 :(得分:0)

将WorkerA和WorkerB包装到从公共基类派生的各个类中,此外还继承自std :: vector(多重继承)。然后简单地将您的地图值定义为指向基类的智能指针(如果您想将工作对象放在堆栈上,则定义常规指针)。