I have non-template class with a templatized constructor. This code compiles for me. But i remember that somewhere i have referred that constructors cannot be templates. Can someone explain whether this is a valid usage?
typedef double Vector;
//enum Method {A, B, C, D, E, F};
struct A {};
class Butcher
{
public:
template <class Method>
Butcher(Method);
private:
Vector a, b, c;
};
template <>
Butcher::Butcher(struct A)
: a(2), b(4), c(2)
{
// a = 0.5, 1;
// b = -1, 1, 3, 2;
// c = 0, 1;
}
Thanks, Gokul.
As long as you are satisfied with automatic type inference, you can use a template constructor (of a non-template class). @updogliu: Absolutely. But, the question is asking about "a template constructor with no arguments" If there are no function arguments, no template arguments may be deduced.
The only way of invoking such a constructor is by letting the compiler deduce the template arguments from the constructor arguments. This also means that a template constructor with no parameters can never be called at all.
Templates in c++ is defined as a blueprint or formula for creating a generic class or a function. To simply put, you can create a single function or single class to work with different data types using templates. C++ template is also known as generic functions or classes which is a very powerful feature in C++.
It's perfectly valid for constructors to be template members. The only thing that I can think that you might be think of is that a template constructor is never a copy constructor so a template constructor won't itself prevent the generation of a compiler generated copy constructor.
Yes, constructors can be templates.
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