2011-08-26 59 views
1

我需要某种方式来实现“反向模板别名”。所以我会使用模板typedef在编译时选择正确的类。我想做到以下几点:反向模板别名

typedef ClassA Temp<int>; 
typedef ClassB Temp<char>; 

ClassA和ClassB的不是模板类,但我想通过使用模板来选择合适的班级。所以如果需要Temp> < int>,它实际上会使用ClassA。在C++中甚至有可能这样吗?我尝试了以下,但它没有奏效。

template<> 
typedef ClassA Temp<int>; 

template<> 
typedef ClassB Temp<char>; 

我得到了以下错误在GCC

error: template declaration of ‘typedef’ 
+0

你能给出你想要实现的代码示例吗?在你的例子中,ClassA和ClassB是具体类型,而不是模板。 –

+0

而且你不能模拟typedef。但是有一些解决方法,取决于你想要做什么。 –

回答

2

没有,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; } 

这样你就可以得到ClassAClassB自己,但你必须写Temp<int>::Type

+0

谢谢!第二个例子正是我想要的。我应该想到这一点。在派生类的例子中,如果我不向模板类添加任何东西,是不是会像使用实际的类一样? – Justin

+0

@Justin:不,它不会是一个正式的类型。你可以将'Temp '实例传递给'ClassA'参数,但不能反过来。 –

+0

我该如何称呼新的? ptr = new Temp :: Type()不起作用。 – Justin