C++ template specialization of constructor

user231536 picture user231536 · Dec 14, 2009 · Viewed 26.5k times · Source

I have a templated class A<T, int> and two typedefs A<string, 20> and A<string, 30>. How do I override the constructor for A<string, 20> ? The following does not work:

template <typename T, int M> class A;
typedef  A<std::string, 20> one_type;
typedef  A<std::string, 30> second_type;


template <typename T, int M>
class A {
public:
  A(int m) {test= (m>M);}

  bool test;

};


template<>
one_type::one_type() { cerr << "One type" << endl;}

I would like the class A<std::string,20> to do something that the other class doesn't. How can I do this without changing the constructor A:A(int) ?

Answer

xtofl picture xtofl · Dec 14, 2009

The only thing you cannot do is use the typedef to define the constructor. Other than that, you ought to specialize the A<string,20> constructor like this:

template<> A<string,20>::A(int){}

If you want A<string,20> to have a different constructor than the generic A, you need to specialize the whole A<string,20> class:

template<> class A<string,20> {
public:
   A(const string& takethistwentytimes) { cerr << "One Type" << std::endl; }
};