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) ?
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.
Explicit (full) specializationAllows customizing the template code for a given set of template arguments.
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.
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.
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; }
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With