Gokul
Gokul

Reputation: 933

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.

Upvotes: 7

Views: 1531

Answers (2)

Andreas Brinck
Andreas Brinck

Reputation: 52549

Yes, constructors can be templates.

Upvotes: 12

CB Bailey
CB Bailey

Reputation: 792487

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.

Upvotes: 13

Related Questions