6

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?

ritter
  • 7,447
  • 7
  • 51
  • 84

2 Answers2

7

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.

Community
  • 1
  • 1
RobH
  • 3,199
  • 1
  • 22
  • 27
0

You could provide a function and a class template, then define a couple of typedefs:

template<class T, class TArg> 
class A 
{   
    void foo(const TArg& arg) {}

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

typedef A<MyType, MyType> NormalClass;
typedef A<MyType, bool>   BoolClass;
Graeme
  • 4,514
  • 5
  • 43
  • 71
  • Thanks, but this is not an option. At instantiation time of `A` I have no knowledge on what type `foo` will be used. Sorry – ritter Oct 16 '12 at 10:47
  • You mean you don't know at compile time the type or at runtime? – Graeme Oct 16 '12 at 10:50