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. If U
were to represent T*
, what would U<int>
be? You probably mean T<int>*
but that doesn't match your declaration, so there is no way to plug that type into A
.
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 call Expander
and set it by default to this:
template <typename T> struct Expander {
typedef T type;
};
Then, when invoking A
you could say
A<int,T> normal;
A<int,T,PtrExpander> pointer;
with
template <typename T> struct PtrExpander {
typedef T* type;
};
and A
would be:
template<typename T, template<typename> class U, template <typename> class E = Expander> class A {
typedef typename E<U<Your_Args_to_U> >::type;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.