问题
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