【发布时间】:2020-07-27 21:33:17
【问题描述】:
如何禁用模板类的复制构造函数。
例如:
template<typename T>
struct X {
T property;
constexpr X(const T property): property(property) { }
friend std::ostream& operator<<(std::ostream& out, const X& x) {
return out << "{ " << x.property << " }";
}
};
问题:
如果我让类包含它自己
constexpr X x1 { 1 };
std::cout << x1 << "\n"; // prints "{ 1 }"
constexpr X x2 { x1 };
std::cout << x2 << "\n"; // prints "{ 1 }", expected "{ { 1 } }"
我的假设是调用了复制构造函数。 删除复制构造函数没有帮助。然后我得到一个编译时错误。
【问题讨论】:
-
Deleting the copy constructor does not help.你是怎么做到的? -
某事模板参数推断。修复它,复制构造函数甚至不会成为构造
x2的候选对象。 -
我删除了
constexpr X(const X&) = delete;的拷贝构造函数。 -
请注意,您不想要删除或禁用复制构造函数,因为
X<X<int>>实例化中的 ctor-initializer 列表将需要它。 -
您的示例无法编译。它在修复 ideone.com/sLdeKH 后工作
标签: c++ templates constructor