如何从复制构造函数委托到通用复制构造函数模板

How delegate from copy constructor to universal copy constructor template?

本文关键字:复制 函数模板 构造函数      更新时间:2023-10-16

如果我想编写一个通用复制构造函数(可以接受任何参数类型),这很容易做到:

class Widget {
public:
  template<typename T> Widget(T&& other);
};

这不会阻止编译器生成传统的复制构造函数,所以我想自己编写并委托给模板。但我该怎么做呢?

class Widget {
public:
  template<typename T> Widget(T&& other);
  Widget(const Widget& other): ??? {}         // how delegate to the template?
};

我试着这样写委托构造函数,

Widget(const Widget& other): Widget<const Widget&>(other){}

但是VC11, gcc 4.8和clang 3.2都拒绝它。

我怎么写我想写的委托复制构造函数?

不能为构造函数模板指定模板参数;你仅限于演绎。也许你可以从我以前的一个帖子中改编一个答案:

// NOT Tested!
#include <utility>
class Widget
{
    enum fwd_t { fwd };
    // Your true master constructor
    template< typename T >  Widget( fwd_t, T &&t );
public:
    template < typename T >
    Widget( T&& other );
        : Widget( fwd, std::forward<T>(other) )
    {}
    Widget( const Widget& other )
        : Widget( fwd, other )
    {}
};

两个单参数构造函数转发给两个参数的兄弟构造函数