为什么委托(delegate)构造函数在模板的情况下不起作用?在 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;
}
*/
};
最佳答案
请注意:模板构造函数永远(!)不是复制构造函数。 相反,将生成一个默认的复制构造函数(如果可能)。
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);
}
关于c++ - 委派构造函数和模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27430584/