如何删除由union成员及其隐式删除的成员函数导致的代码重复?

时间:2016-05-04 03:22:48

标签: c++

我有一个模板类C<T>,当C<U>可以使用T构建时,U可以实例化。如下面的代码所示,我有一些重复的代码;我可以将调用推迟到模板copy-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;
    };
};

有更好的方法吗?此标签发送是否会导致任何性能损失?如果是这种情况,我宁愿重复代码。

1 个答案:

答案 0 :(得分:0)

我离开了我的电脑,所以目前无法对此进行测试,但你可能会通过使用一些间隙类型而不是虚拟参数强制分辨率:

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}) {}
};

不知道这可以被内联得多好或者开销会是多少,而且它是否真的代表了你的标签参数的可读性增加。