Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 467
Enrico Granata Avatar asked Aug 18 '11 19:08

Enrico Granata


People also ask

Why template partial specialization?

Partial template specialization is a particular form of class template specialization. Usually used in reference to the C++ programming language, it allows the programmer to specialize only some arguments of a class template, as opposed to explicit full specialization, where all the template arguments are provided.

What represents partial specialization?

You can choose to specialize only some of the parameters of a class template. This is known as partial specialization. Note that function templates cannot be partially specialized; use overloading to achieve the same effect.

What is meant by template specialization?

The act of creating a new definition of a function, class, or member of a class from a template declaration and one or more template arguments is called template instantiation. The definition created from a template instantiation is called a specialization.

What are the two types of templates?

There are two types of templates in C++, function templates and class templates.


1 Answers

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.

like image 134
Johannes Schaub - litb Avatar answered Oct 08 '22 03:10

Johannes Schaub - litb