本文介绍了一个模板化的构造函数可以代替一个被删除的拷贝构造函数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 考虑template<typename T>struct Foo{ Foo(const Foo&) = delete; template <typename Y> Foo(const Foo<Y>&){}};模板构造函数的适当实例化是否代表复制构造函数?我知道它不正常(因为复制构造函数不能是一个模板函数),但在这里我已经删除了复制构造函数。Does the appropriate instantiation of the template constructor stand in for the copy constructor? I know it doesn't normally (since the copy constructor must not be a template function) but here I've deleted the copy constructor.推荐答案不能:重载解析始终考虑非模板函数,当遇到 delete d时,重载解析失败No it can't: overload resolution always considers non-templated functions first, and when a deleted one is encountered, overload resolution fails rather than a template overload being considered.允许我使用 Foo()= default;然后,考虑两个变量Foo<double> double_foo;Foo<int> int_foo;然后注意 Foo< int>由于模板,允许使用(double_foo); Foo< int&由于 delete d构造函数不允许使用(bar_foo) > Foo< int>如果您已通过写入重新引入 move constructor ,则允许使用 = bar = Foo (); 。这里需要使用 = 语法,因为 Foo< int>Foo<int> bar(double_foo); is allowed due to the templateFoo<int> bar(int_foo); is not allowed due to the deleted constructorFoo<int> bar = Foo<int>(); would be allowed if you had re-introduced the move constructor by writing Foo(const Foo&&) = default;. You need to use the = syntax here since Foo<int> bar(Foo<int>()); is a forward declaration.最后,你的断言复制构造函数不能是模板函数是不正确的。信用@LightnessRacesInOrbit:Finally, your assertion "the copy constructor must not be a template function" is not correct. Credit to @LightnessRacesInOrbit: C ++ 14 12.8.2类X的非模板构造函数是副本如果它的第一个参数是类型X& const X& volatile X&或const volatile X&,并且没有其他参数或 else所有其他参数都有默认参数6)。 C++14 12.8.2 "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 (8.3.6). 这篇关于一个模板化的构造函数可以代替一个被删除的拷贝构造函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-18 13:30