Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does a templated constructor override the implicit copy constructor in C++?

Does a templated constructor (such as the following) override the implicit copy constructor?

template <class T>
struct Foo
{
    T data;

    // ...

    template <class U>
    Foo(const Foo<U> &other) : data((T)doSomethingWith(other.data)) {}

    // ...
};

If so, does it still override it if other is passed by value rather than constant reference?

If so, is there any way around this without explicitly defining a copy constructor?

like image 758
Matt Avatar asked Jun 13 '12 13:06

Matt


2 Answers

No, that is not a copy constructor. Section 12.8 ([class.copy]) of the Standard requires that:

A non-template constructor for class X is a copy constructor if its first parameter is of type X&, const X&, volatile X& or const volatile X&, and either there are no other parameters or else all other parameters have default arguments.

The compiler will still implicitly generate a defaulted one.

You can make that explicit (requires C++11) by

Foo(const Foo<T>&) = default;
like image 160
Ben Voigt Avatar answered Sep 27 '22 18:09

Ben Voigt


Does a templated constructor (such as the following) override the implicit copy constructor?

No. The copy constructor is still implicitly declared, and is chosen in preference to the template.

Is there any way around this without explicitly defining a copy constructor?

No. If you don't want the implicit copy constructor, then you'll have to define one yourself.

like image 41
Mike Seymour Avatar answered Sep 27 '22 19:09

Mike Seymour