【发布时间】:2019-05-31 17:32:27
【问题描述】:
考虑以下 C++ 代码,我尝试避免 preference of non-template copy&move constructors and assignment operators 失败:
template<typename T> class A {
public:
A() { /* implementation here */ }
// Remove from the overloads the default copy&move constructors and assignment operators
A(const A&) = delete;
A& operator=(const A&) = delete;
A(A&&) = delete;
A& operator=(A&&) = delete;
// I want these to be used e.g. by std::vector
template<typename U> A(const A<U>& fellow) { /* implementation here */ }
template<typename U> A& operator=(const A<U>& fellow) { /* implementation here */ }
template<typename U> A(A<U>&& fellow) { /* implementation here */ }
template<typename U> A& operator=(A<U>&& fellow) { /* implementation here */ }
};
但是,我收到以下错误
试图引用已删除的函数
当尝试将 A 项目推送到向量或简单地复制构造时:
A<int> a1{};
A<int> a2(a1);
UPDATE1:我需要模板复制和移动构造函数和赋值运算符,因为模板参数实际上只是控制一些缓存,所以A<T1> 可以安全地分配给A<T2>。
【问题讨论】:
-
复制/移动构造函数永远不是模板。如果您不希望复制/移动构造函数完成工作,也许您可以委托。显示实施的哪一部分让您感到困扰;它可能最好放在任何构造函数之外。
-
A<int> a1();是一个函数声明(“最烦人的解析...”)而且所有的构造函数都是私有的 -
而不是
delete常规的复制/移动构造函数/赋值,将它们转发到模板实现。 -
@Jarod42,你说的转发具体是什么意思?看来这就是我要的 - 如何转发。
-
@SergeRogatch - 您可以在模板构造函数中转发添加未使用的参数(具有默认值)
标签: c++ templates copy-constructor assignment-operator default-constructor