如何删除由联合成员及其隐式删除的成员函数引起的代码重复

How can I remove code duplication caused by an union member and its implicitly deleted member functions?

本文关键字:删除 成员 函数 代码 何删除      更新时间:2023-10-16

我有一个模板类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}) {}
};

不知道它的内联效果如何,也不知道开销会是多少,这是否真的代表了对标记参数的可读性提高,还有待商榷。