Enrico Granata
Enrico Granata

Reputation: 3329

partial template specialization

I have a scenario in which there is a template class

template<typename X, typename Y>
class Foo
{
 typedef Y::NestedType Bar;

 int A (Bar thing);
 void B();
 int C(X that);

 // other stuff
};

and then I would like the A() method to have a different behavior when X is a given type (but B and C can stay the same, and the actual code actually has about 10 other methods, a few of which are quite lengthy and subject to frequent tweaking.. so I would rather avoid making a full-class specialization and copy&paste the full class implementation)

I went on and wrote:

template<typename T>
int Foo<MyType, T>::A(Bar thing);

but my compiler (clang 163.7.1) refused to even consider this as a template specialization of any sort.

Is there some syntax error hidden in the way I wrote the code, or is this coding style invalid C++? Unfortunately, even if other compilers do support the idiom, my company is stuck with clang.

Thanks for any help on this.

Upvotes: 7

Views: 2206

Answers (1)

Johannes Schaub - litb
Johannes Schaub - litb

Reputation: 506837

Use overloading

template<typename X, typename Y>
class Foo
{
 // allows to wrap up the arguments
 template<typename, typename>
 struct Types { };

 typedef Y::NestedType Bar;

 int A (Bar thing) {
   return AImpl(thing, Types<X, Y>());
 }

 void B();
 int C(X that);

 // other stuff
private:
  template<typename X1, typename Y1>
  int AImpl(Bar thing, Types<X1, Y1>) {
    /* generic */
  }

  template<typename Y1>
  int AImpl(Bar thing, Types<SpecificType, Y1>) {
    /* special */
  }
};

You cannot partially specialize a member of a class template. What you wrote would be the definition of a member function A of a partial specialization of the class template itself.

Upvotes: 7

Related Questions