Reverse Template Alias
I need some way to achieve a "reverse template alias". So I'd use a template typedef to select the correct class to use at compile time. I'd like to do the following:
typedef ClassA Temp<int>;
typedef ClassB Temp<char>;
ClassA and ClassB are not template classes, but I'd like to select the right class through the use of a te开发者_Go百科mplate. So if a Temp< int > was needed it would actually use ClassA. Is anything like this even possible in C++? I tried the following but it didn't work.
template<>
typedef ClassA Temp<int>;
template<>
typedef ClassB Temp<char>;
I got the following error in GCC
error: template declaration of ‘typedef’
No, typedef
can't define type templates, only types. The two closest things you can do are:
template <typename T>
struct Temp;
template <>
struct Temp<int> : ClassA {}
template <>
struct Temp<char> : ClassB {}
so you write just Temp<int>
, but it's a derived class, not the class itself, or
template <typename T>
struct Temp;
template <>
struct Temp<int> { typedef ClassA Type; }
template <>
struct Temp<char> { typedef ClassB Type; }
so you can get the ClassA
and ClassB
themselves, but you have to write Temp<int>::Type
.
精彩评论