Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid repeating the whole class template when only one member specialization is needed

Suppose you have:

template<class T>
class A {
  template<class T1> 
  void foo(const T1& t1) {}

  //
  // Lots of other definitions (all templated)
  // 
};

and you would like to specialize foo(const T1&) but only for a specialized A<bool>. Like this:

template<>
class A<bool> {
  template<class T1> 
  void foo(const T1& t1) {
    // Code for specialized A<boo>::foo
  }

  //
  // Repeating the former definitions, how to avoid this ??
  // 
};

But to get this to work I have to duplicate all the code that is defined in the class template class A and include it again in class A<bool>.

I tried to define only the member specialization:

template<>
void A<bool>::template<class T1> foo(const T1&) {}

Neither does this work:

template <class T1> void A<bool>::foo(const T1&) {}

But the compiler doesn't like it. What's the way to deal with this code duplication?

like image 457
ritter Avatar asked Oct 16 '12 10:10

ritter


People also ask

How will you restrict the template for a specific datatype?

There are ways to restrict the types you can use inside a template you write by using specific typedefs inside your template. This will ensure that the compilation of the template specialisation for a type that does not include that particular typedef will fail, so you can selectively support/not support certain types.

Can there be more than one arguments to templates?

Can there be more than one argument to templates? Yes, like normal parameters, we can pass more than one data type as arguments to templates.

What is the difference between generic class template and specialization template?

Key differences between generics and C++ templates: Generics are generic until the types are substituted for them at runtime. Templates are specialized at compile time so they are not still parameterized types at runtime. The common language runtime specifically supports generics in MSIL.

What is explicit template specialization?

Explicit (full) specializationAllows customizing the template code for a given set of template arguments.


1 Answers

Syntax? See this answer. Try:

template<>
template<typename T1>
void A<bool>::foo(const T1&){}

You certainly don't need to copy the whole class template.

like image 167
RobH Avatar answered Sep 20 '22 04:09

RobH