C++ template copy constructor on template class

懵懂的女人 提交于 2019-11-27 09:41:47
Barry

A copy constructor is of the form X(X& ) or (X const&) and will be provided for you by the compiler if you didn't declare one yourself (or a few other conditions which are not relevant here). You didn't, so implicitly we have the following set of candidates:

MyTemplateClass(const MyTemplateClass&);
template <typename U> MyTemplateClass(const MyTemplateClass<U>&);

Both are viable for

MyTemplateClass<int> instance2(instance);

Both take the same exact arguments. The issue isn't that your copy constructor template doesn't match. The issue is that the implicit copy constructor is not a function template, and non-templates are preferred to template specializations when it comes to overload resolution. From [over.match.best], omitting the unrelated bullet points:

Given these definitions, a viable function F1 is defined to be a better function than another viable function F2 if for all arguments i, ICSi(F1) is not a worse conversion sequence than ICSi(F2), and then
— [...]
— F1 is not a function template specialization and F2 is a function template specialization, or, if not that,
— [...]

That's why it calls your implicit (and then, your explicit) copy constructor over your constructor template.

When you do not have a copy constructor in you code, the compiler will implicitly generate it. Therefore when this line is executed:

MyTemplateClass<int> instance2(instance);

A copy constructor is being executed, though obviously not yours. I think that templating has nothing to do with it.

Read more about it here: Implicitly-defined copy constructor

stellarpower

I think REACHUS is right. The compiler is generating a default copy-constructor (as it would with a non-template class too) and preferring this over your template as it's more specialised.

You should make your "normal" copy-constructor private, or better, use the C++11 'deleted' keyword to mark the function as unusable.

However, this doesn't compile. Sorry, I wasn't able to test it at the time.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!