我需要一些方法来实现“反向模板别名”。因此,我将使用模板 typedef 来选择要在编译时使用的正确类。我想执行以下操作:
typedef ClassA Temp<int>;
typedef ClassB Temp<char>;
ClassA 和 ClassB 不是模板类,但我想通过使用模板来选择正确的类。因此,如果需要 Temp
template<>
typedef ClassA Temp<int>;
template<>
typedef ClassB Temp<char>;
我在 GCC 中遇到以下错误
error: template declaration of ‘typedef’
最佳答案
不,typedef
不能定义类型模板,只能定义类型。您可以做的最接近的两件事是:
template <typename T>
struct Temp;
template <>
struct Temp<int> : ClassA {}
template <>
struct Temp<char> : ClassB {}
所以你只写Temp<int>
, 但它是一个派生类,而不是类本身,或者
template <typename T>
struct Temp;
template <>
struct Temp<int> { typedef ClassA Type; }
template <>
struct Temp<char> { typedef ClassB Type; }
所以你可以获得ClassA
和 ClassB
自己,但你必须写 Temp<int>::Type
.
关于c++ - 反向模板别名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7201503/