委派构造函数和模板

时间:2014-12-11 19:11:14

标签: c++ templates delegates copy-constructor

为什么在模板的情况下委托构造函数不起作用?复制构造函数不会在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;
    }
*/
};

1 个答案:

答案 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);
}