I have a problem with nested templates and their template specialization. Given the following classes:
A small template class
template<class U>
class T {
public:
T(){}
virtual ~T (){}
};
And some kind of nested template
template<typename T, template<typename> class U>
class A {
public:
void foo()
{
std::cerr << "A generic foo";
}
};
And a small 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;
}
Now I need a specialization if U is a pointer:
A<double,T*> *b = new A<double,T*>;
b->foo();
How to achieve this? I tried something like:
template<typename T, template<typename> class U>
class A< T, U* >
{
public:
void foo()
{
std::cerr << "A specialized foo";
}
};
But it just resolves in
A.h:18:16: Error: Templateargument 2 is invalid
What you’re tying to do is not possible, because
T*has no meaning. Neither is it a proper type, nor does it match a template, which requires additional parameters. IfUwere to representT*, what wouldU<int>be? You probably meanT<int>*but that doesn’t match your declaration, so there is no way to plug that type intoA.Since you asked for a way to get around this, from the top of my head, something like this.
Accept a third template argument to
A, which I would callExpanderand set it by default to this:Then, when invoking
Ayou could saywith
and
Awould be: