我遇到嵌套模板及其模板专业化的问题。鉴于以下类别:
小模板类
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
答案 0 :(得分:0)
你不能做什么,因为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;