【发布时间】:2020-11-16 09:15:15
【问题描述】:
我试图为一个类模板实现一个复制构造函数,它允许所有实例化从一个版本的类模板转换为另一个版本。
这导致以下代码
#include <memory>
#include <iostream>
template<bool binary>
class Bar {
private:
friend class Bar<!binary>;
std::unique_ptr<int> data;
public:
Bar(int example) : data(std::make_unique<int>(example)) {
}
template<bool value>
Bar(const Bar<value>& bar) : data(std::make_unique<int>(*bar.data)) {
}
//other methods that differ depending on binary value...
};
int main() {
Bar<false> b1{ 1 };
Bar<false> b2{ b1 }; //causes compile error
Bar<true> b3{ b1 }; //works as expected
}
从不同类型构造可以工作,但从相同类型构造会发出编译时错误提示
Bar::Bar(const Bar &)': 试图引用一个 删除功能
显然没有调用通用复制构造函数,这导致我手动写出复制构造函数,导致当前代码。
#include <memory>
#include <iostream>
template<bool binary>
class Bar {
private:
friend class Bar<!binary>;
std::unique_ptr<int> data;
public:
Bar(int example) : data(std::make_unique<int>(example)) {
}
Bar(const Bar& bar) : data(std::make_unique<int>(*bar.data)) {
}
template<bool value>
Bar(const Bar<value>& bar) : data(std::make_unique<int>(*bar.data)) {
}
//other methods that differ depending on binary value...
};
int main() {
//all work as expected.
Bar<false> b1{ 1 };
Bar<false> b2{ b1 };
Bar<true> b3{ b1 };
Bar<true> b4{ b3 };
}
值得注意的是,这对于移动构造函数、复制赋值运算符和移动赋值运算符也是必需的。 因此,我有两个问题
- 为什么通用复制或移动构造函数不会覆盖复制/移动构造函数?
- 是否有更好的解决方法来允许相同类型和替代类型的复制构造?截至目前,我基本上必须为每个复制/移动构造函数和赋值运算符复制代码。
【问题讨论】:
标签: c++ templates copy-constructor unique-ptr