How delegate from copy constructor to universal copy constructor template?

元气小坏坏 提交于 2020-01-14 03:55:09

问题


If I want to write a universal copy constructor (one that will take any argument type), it's easy enough to do:

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

This won't prevent the compiler from generating a traditional copy constructor, so I'd like to write that myself and delegate to the template. But how do I do that?

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

I tried to write the delegating constructor this way,

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

but VC11, gcc 4.8, and clang 3.2 all reject it.

How can I write the delegating copy constructor I'm trying to write?


回答1:


You can't specify template arguments for a constructor template; you're limited to deduction. Maybe you can adapt an answer from one of my old posts:

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

The two single-argument constructors forward to a two-argument sibling constructor.



来源:https://stackoverflow.com/questions/15264252/how-delegate-from-copy-constructor-to-universal-copy-constructor-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!