C ++: partial specialization of template classes

The following code:

using namespace std; template <typename X> class Goo {}; template <typename X> class Hoo {}; template <class A, template <typename> class B = Goo > struct Foo { B<A> data; void foo1(); void foo2(); }; template <typename A> void Foo<A>::foo1() { cout << "foo1 for Goo" << endl;} int main() { Foo<int> a; a.foo1(); } 

gives a compiler error:

 test.cc:18: error: invalid use of incomplete type 'struct Foo<A, Goo>' test.cc:11: error: declaration of 'struct Foo<A, Goo>' 

Why can't I partially specialize in foo1 ()? If this is not the case, how should I do it?

I have another question: what if I want foo2 () to be defined only for A = int, B = Hoo and not for any other combination, how can I do this?

+7
source share
2 answers

Function templates can be fully specialized, and not partly.

The member functions of class templates are automatically functional templates, and they can indeed be specialized, but only completely:

 template <> void Foo<int, Goo>::foo1() { } // OK 

You can partially specialize the entire class and then redefine it:

 template <typename A> struct Foo<A, Goo> { // ... }; 

(for more details see 14.7.3.)

+4
source

The template still has two parameters, and you should write something like this:

 template <typename A, template <typename> class B> void Foo<A,B>::foo1() { cout << "foo1" << endl;} 

The default value is specified and should be specified only once. From now on, he, like any other two-parameter template. This code will be applied no matter what is B (by default or otherwise). If you want to specify other behavior for a specific B, then you specialize in a class, not just a method.

( Heavily edited )

+1
source

All Articles