简体   繁体   中英

C++ map a template derived class

Hi I have a the following structures and data types:

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;

I need a direction to create a const map between EWorkerType::WorkerType1 to WorkerA and EWorkerType::WorkerType2 to WorkerB.

I tried this direction

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

You may use something like (for compile time):

template <EWorkerType> struct WorkersMapping;

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

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

or if your enum values is correctly chosen, something like:

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

Wrap WorkerA and WorkerB into respective classes derived from a common base class, in addition to also inheriting from std::vector (multiple inheritance). Then simply define your map value as a smart pointer to the base class (or a regular pointer if you want to put the worker objects on the stack).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM