我有一个嵌套模板和他们的模板专门化的问题。给定以下类:
一个小的模板类
template<class U>
class T {
public:
T(){}
virtual ~T (){}
};以及某种嵌套的模板
template<typename T, template<typename> class U>
class A {
public:
void foo()
{
std::cerr << "A generic foo";
}
};和一个小的main.cpp
int main(int argc, const char *argv[])
{
A<int,T> *a = new A<int,T>;
a->foo();
//This wont work:
A<double,T*> *b = new A<double,T*>;
b->foo();
return 0;
}现在,如果U是一个指针,我需要一个特殊化:
A<double,T*> *b = new A<double,T*>;
b->foo();如何做到这一点?我试过这样的方法:
template<typename T, template<typename> class U>
class A< T, U* >
{
public:
void foo()
{
std::cerr << "A specialized foo";
}
};但它只是解决了
A.h:18:16: Error: Templateargument 2 is invalid发布于 2012-04-07 03:06:51
你想要做的事情是不可能的,因为T*没有任何意义。它既不是正确的类型,也不匹配需要额外参数的模板。如果U代表T*,U<int>会是什么?您的意思可能是T<int>*,但它与您的声明不匹配,因此无法将该类型插入到A中。
既然你想找个办法绕过这件事,从我的脑海里看,就像这样。
接受A的第三个模板参数,我将其称为Expander,并将其默认设置为:
template <typename T> struct Expander {
typedef T type;
};然后,在调用A时,您可以这样说
A<int,T> normal;
A<int,T,PtrExpander> pointer;使用
template <typename T> struct PtrExpander {
typedef T* type;
};而A将是:
template<typename T, template<typename> class U, template <typename> class E = Expander> class A {
typedef typename E<U<Your_Args_to_U> >::type;https://stackoverflow.com/questions/10047780
复制相似问题