Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ template specialization of constructor

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) ?

like image 669
user231536 Avatar asked Dec 14 '09 19:12

user231536


People also ask

Can constructor be a template function?

Destructors and copy constructors cannot be templates. If a template constructor is declared which could be instantiated with the type signature of a copy constructor, the implicitly-declared copy constructor is used instead.

What is explicit template specialization?

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

What does template <> mean in C ++?

Templates are a feature of the C++ programming language that allows functions and classes to operate with generic types. This allows a function or class to work on many different data types without being rewritten for each one.

Can you partially specialize a C++ function template?

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.


1 Answers

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; }
};
like image 160
xtofl Avatar answered Oct 05 '22 22:10

xtofl