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

C++ 如何删除由联合成员及其隐式删除的成员函数导致的代码重复?,c++,C++,我有一个模板类C,当T可以用U构造时,它应该可以用C实例化。正如下面的代码所示,我有一些重复的代码;我可以将呼叫推迟到模板复制管理员吗 template <typename T> class C { public: C() {} ~C() {} template <typename U> C( C<U> const& other ) { /* ... duplicate code ... */ } // re

我有一个模板类
C
,当
T
可以用
U
构造时,它应该可以用
C
实例化。正如下面的代码所示,我有一些重复的代码;我可以将呼叫推迟到模板复制管理员吗

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;
    };
};
模板
C类
{
公众:
C(){}
~C(){}
模板
C(C常量和其他){/*…重复代码…*/}
//必需,因为union会自动将此重载声明为已删除
C(C常量和其他){/*…重复代码…*/}
私人:
联盟
{
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;
    };
};
struct-ctor\u-tag\u-t{};
模板
C类
{
公众:
C(){}
~C(){}
模板
C(C const&other,ctor_tag_t=ctor_tag_t{}{/*…code…*/}
C(C const&other):C(other,ctor_tag{}){
私人:
联盟
{
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}) {}
};
模板
结构虚拟
{
T const&T;
虚拟(T常数&T):T(T){}
运算符T常量&({return T;}
};
模板
C类
{
公众:
模板
C(施工及其他);
C(C常数与其他):C(伪{other}){
};

不知道这可以内联到什么程度,或者开销会是什么,这是否真的代表了标记参数可读性的提高,还有待讨论。

为什么不用
T;}
替换
union{T;}
?@immibis,因为这需要
DefaultConstructible
。在联合中包装
t
的目的是什么?据我所知,它只会使代码变得不必要的复杂。它可能有助于展示一些在您想要支持的用例中使用此类的示例代码。如果两个构造函数必须执行相同的任务,您可以使用委托构造函数。事实上,您在当前的解决方案中确实做到了这一点