Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can C++ Constructors be templates?

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.

like image 358
Gokul Avatar asked Apr 23 '10 07:04

Gokul


People also ask

Can you template a constructor?

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.

How do you call a constructor template?

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.

Why are templates used in C++?

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++.


2 Answers

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.

like image 58
CB Bailey Avatar answered Oct 01 '22 05:10

CB Bailey


Yes, constructors can be templates.

like image 23
Andreas Brinck Avatar answered Oct 01 '22 04:10

Andreas Brinck