c++ - 委派构造函数和模板

标签 c++ templates delegates copy-constructor

为什么委托(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/

相关文章:

c++ - 分离与合并由静态语言的数据库表制成的对象

c++ - 从模板包生成所有大小为 N 的子包

c++ - 在 B 类中声明为友元的 A 类成员模板函数无法访问 A 类的私有(private)成员(仅限 Clang)

ios - 确定何时将 subview 添加到 tableView

iphone - iOS:通知其他选项卡式 View Controller 有关其数据集的更改

c++ - Android NDK OpenGL ES 2 上下文初始化

c++ - sem_destroy 一个信号量被其他人持有 sem_wait?

c++ - malloc/free 用于调整数组大小

C++模板和结构问题

c# - 在 C# 中为所有事件和委托(delegate)创建一个包罗万象的处理程序