C++ template copy constructor on template class

前端 未结 3 664
半阙折子戏
半阙折子戏 2020-11-29 13:13

I have a template class that has a template copy constructor. The problem is when I instantiate this class using another instance of this class with the same template type,

3条回答
  •  被撕碎了的回忆
    2020-11-29 13:53

    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  MyTemplateClass(const MyTemplateClass&);
    

    Both are viable for

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

提交回复
热议问题