Ser*_*tch 5 c++ templates copy-constructor default-constructor assignment-operator
考虑以下C++代码,我试图避免偏向非模板复制和移动构造函数和赋值运算符:
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 */ }
};
Run Code Online (Sandbox Code Playgroud)
但是,我收到以下错误
试图引用已删除的功能
当试图将A项目推送到矢量或简单地复制构造,如:
A<int> a1{};
A<int> a2(a1);
Run Code Online (Sandbox Code Playgroud)
UPDATE1:我需要模板复制和移动构造函数和赋值运算符,因为模板参数实际上只是控制一些缓存,因此A<T1>可以安全地分配给A<T2>.
您可以通过使用备用签名声明已删除的复制构造函数/赋值运算符来使编译器满意,这不会导致选择此重载但会阻止编译器生成构造函数/赋值运算符:
template<typename T> class A
{ public:
A() { /* implementation here */ }
// Remove from the implicit declaration of the default copy&move constructors and assignment operators
A(A volatile const &) = delete;
A & operator =(A volatile const &) = delete;
// I want these to be used e.g. by std::vector
template<typename U> A(A<U> const & fellow) { /* implementation here */ }
template<typename U> A & operator =(A<U> const & fellow) { /* implementation here */ return *this;}
template<typename U> A(A<U> && fellow) { /* implementation here */ }
template<typename U> A & operator =(A<U> && fellow) { /* implementation here */ return *this; }
};
int main()
{
A<int> a1{};
A<int> a2{a1};
return 0;
}
Run Code Online (Sandbox Code Playgroud)
15.8.1复制/移动的构造[class.copy.ctor]
1.一种非模板的构造class X是一个拷贝构造如果其第一个参数的类型为X&,const X&,volatile X&或const volatile X&,并且或者没有其他参数或者所有其他参数有默认参数
| 归档时间: |
|
| 查看次数: |
134 次 |
| 最近记录: |