简体   繁体   中英

partially specialized template as a trait member type

I want to choose a template from a trait class, like in the following:

template<typename T>
class JobTypeA { };

template<typename T>
class JobTypeB { };

template<typename T>
class JobTraits
{
    /* nothing */
};

class A { };

template<>
class JobTraits<A>
{
    typedef JobTypeA Type;
};

class B {};

template<>
class JobTraits<B>
{
    typedef JobTypeB Type;
};

class JobTarget1 { };
class JobTarget2 { };

template<typename T, typename U>
class JobUser
{
public:
    typedef typename JobTraits<T>::Type<U> JobType;

    void doSomething (void)
    {
        JobType j;
        /*... */
    }
};

int
main (void)
{
    JobUser<B, JobTarget1> j;
}

The above wont compile because of the "typedef of an incomplete type" in the specialized traits classes. I got this working using 'alias templates' in std=c++11 with g++ 4.7.2. However VS2010 does not support it yet. Are there any workarounds to achieve the same without 'alias templates'.

How about

template<typename U>
struct Type
{
   typedef JobTypeA<U> type;
};

and

template<typename U>
struct Type
{
   typedef JobTypeB<U> type;
};

Usage:

typedef typename JobTraits<T>::template Type<U>::type JobType;

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