如何删除由联合成员及其隐式删除的成员函数引起的代码重复
How can I remove code duplication caused by an union member and its implicitly deleted member functions?
我有一个模板类C<T>
,当T
可以用U
构造时,它应该与C<U>
实例化。如下面的代码所示,我有一些重复的代码;我可以推迟调用模板复制ctor吗?
template <typename T>
class C
{
public:
C() {}
~C() {}
template <typename U>
C( C<U> const& other ) { /* ... duplicate code ... */ }
// required, since union automatically declares this overload as deleted
C( C const& other ) { /* ... duplicate code ... */ }
private:
union
{
T t;
};
};
我目前的解决方案如下:
struct ctor_tag_t {};
template <typename T>
class C
{
public:
C() {}
~C() {}
template <typename U>
C( C<U> const& other, ctor_tag_t = ctor_tag_t{} ) { /* ... code ... */ }
C( C const& other ) : C( other, ctor_tag_t{} ) {}
private:
union
{
T t;
};
};
有更好的方法吗?这个标签调度会对性能造成影响吗?如果是这样的话,我宁愿重复代码。
我不在电脑旁,所以目前无法测试,但你可能会通过使用一些间隙类型而不是使用伪参数来强制分辨率:
template <typename T>
struct dummy
{
T const& t;
dummy (T const& t): t(t) {}
operator T const&() { return t; }
};
template <typename T>
class C
{
public:
template <typename U>
C (U const& other);
C (C const& other): C (dummy<C>{other}) {}
};
不知道它的内联效果如何,也不知道开销会是多少,这是否真的代表了对标记参数的可读性提高,还有待商榷。
相关文章:
- 为什么类中的ostringstream类型的成员会导致";调用隐含删除复制构造函数";错误
- std::ofstream 作为类成员删除复制构造函数?
- 删除C++继承中虚拟类成员的代码重复
- 在对象指针上调用 Delete 是否会递归删除其动态分配的成员
- 我可以在此模板中删除此类成员吗?
- 在运行时有条件地删除类成员或跳过调用该成员对象的构造函数
- 指向重载静态成员的函数指针 - 在unique_ptr中用作自定义删除器
- 派生的成员 通过指向基、static_cast、crtp、删除模板的指针
- 删除类成员的动态分配内存的最佳方法是什么
- C++类析构函数删除成员(如果"owner"?
- 在Visual Studio中删除成员std::vector::d ata()
- 为什么删除成员变量的复制构造函数不会阻止默认的复制构造函数
- 队列类中的非空删除成员函数
- 基于模板参数删除成员
- C++11 中已删除成员函数的确切语义是什么?
- 在C++中正确删除成员数组
- C++删除成员函数中的临时节点
- 在c++中,从结构体中删除成员会产生错误
- 如何删除成员函数中的成员数组,以便重新分配
- 状态设计模式 - 不想删除成员类中的此指针