【问题标题】:Delegating constructors and templates委托构造函数和模板
【发布时间】:2015-02-10 09:26:26
【问题描述】:

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

【问题讨论】:

  • @AntonSavin,是的,但不是 T=U。
  • @DieterLücking,即使没有template &lt;typename U&gt;?

标签: c++ templates delegates copy-constructor


【解决方案1】:

请注意:模板构造函数永远不是(!)复制构造函数。 将生成一个默认的复制构造函数,而不是(如果可能的话)。

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

【讨论】:

    猜你喜欢
    • 2020-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-22
    • 2020-02-21
    • 1970-01-01
    相关资源
    最近更新 更多