为什么在模板的情况下委托构造函数不起作用?复制构造函数不会在T=U
的情况下调用常量复制构造函数,尽管没有template <typename U>
和<U>
,它可以正常工作。
template <typename T>
struct Class {
Class () {
std::cout << "Default constructor" << std::endl;
}
template <typename U>
Class (const Class<U>& rhs) {
std::cout << "Const copy constructor" << std::endl;
}
template <typename U>
Class (Class<U>& rhs)
: Class (const_cast<const Class<U>&> (rhs))
{
std::cout << "Copy constructor (templated)" << std::endl;
}
/* // DOES NOT WORK WITHOUT THE NEXT:
Class (Class& rhs)
: Class (const_cast<const Class&> (rhs))
{
std::cout << "Copy constructor (not templated)" << std::endl;
}
*/
};
答案 0 :(得分:2)
请注意:模板构造函数永远不是(!)复制构造函数。 将生成默认的复制构造函数(如果可能)。
struct NoCopy
{
NoCopy() {}
NoCopy(const NoCopy&) = delete;
};
template <typename T>
struct Test
{
NoCopy member;
Test() {};
template <typename U>
Test(const Test<U>&)
{}
};
int main()
{
Test<int> a;
// The following error shows the missing generation of a default constructor,
// due to the non copyable member. Without that member, the code compiles.
// error: use of deleted function ‘Test<int>::Test(const Test<int>&)’
Test<int> b(a);
}