Re: template copy constructor vs normal copy constructor
On Oct 9, 4:23 pm, Blanchet Florian <flo...@wanadoo.fr> wrote:
[...]
If it was just "its first parameter is of type X&,...", the result of
struct A { template<class T> A(T&){std::cout << 0} };
int main() { A a; A b(a); return 0; }
would be "0", because the template constructor A<A>(A&) is a
constructor and is first parameter is of type A&. And the
result isn't "0".
It should be. The fact that the template is not a copy
constructor means that the compiler will generate one. With the
signature (here): A(T const&). But the template function
remains a better match if the object is a non-const lvalue, as
is the case here, so it gets chosen over the compiler generated
copy constructor.
If the template had the signature A(T const&), this would not be
the case, since both it and the compiler generated constructors
would be equally good matches, and when all other things are
equal, a non-template function wins over a template function.
Even if it isn't a "strict" copy constructor, it's called
"generalized copy constructor" by some programmers (like
Meyers, cf Eff++ Item 45).
It's partially a question of context. In the context of the
standard, the presence of a user defined "copy constructor"
prevents the compiler from generating a default copy
constructor. And that is all "copy constructor" means in the
standard. There is no preference for a copy constructor when
copying, for example; normal overload resolution applies. In
everyday speach, however, it's more or less normal to consider
any constructor which "copies", or which is used to copy, a copy
constructor. This is (I'm fairly sure) what Meyers means by
"generalized copy constructor".
--
James Kanze