如何从拷贝构造函数委托到通用拷贝构造函数模板? [英] How delegate from copy constructor to universal copy constructor template?
问题描述
如果我想写一个通用拷贝构造函数(一个将接受任何参数类型),它很容易做到:
class Widget {
public:
template< typename T>小部件(T& amp;其他);
};
这不会阻止编译器生成一个传统的复制构造函数,所以我想写自己和委托模板。
class Widget {
public:
template< typename T>小部件(T& amp;其他);
Widget(const Widget& other):? {} //如何委托给模板?
};
我试着以这种方式编写委托构造函数,
Widget(const Widget& other):Widget< const Widget&>(other){}
但是VC11,gcc 4.8和clang 3.2都拒绝它。
如何写委托复制构造函数I'
您不能为构造函数模板指定模板参数;
你只能扣除。也许您可以从以下某个回答中调整我的旧帖子: //未测试!
#include< utility>
class Widget
{
enum fwd_t {fwd};
//你的真正的主构造函数
template<类型名T>小部件(fwd_t,T& t);
public:
template<类型名T>
Widget(T& other;);
:Widget(fwd,std :: forward< T>(other))
{}
Widget(const Widget& other)
:Widget(fwd,other)
{}
};
两个单参数构造函数转发到双参数兄弟构造函数。
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?
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.
这篇关于如何从拷贝构造函数委托到通用拷贝构造函数模板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!