这三种写法是正确的吗?有什么区别?
class A
{
public:
std::vector<int> a;
A(const A &that)
{
this->a=std::forward<const A&>(that).a; //写法1
//this->a=std::forward<const A>(that).a; //写法2
//this->a=std::forward<A>(that).a; //写法3,会报错
}
};
vector中类型是int啊
const是参与函数重载,参数性质确定的
问题出在于你的构造函数参数that用了const。
模板函数forward定义如下:
template< class T >
T&& forward( typename std::remove_reference<T>::type& t ) noexcept;
当T为const A&或者const A时,std::remove_reference::type& 就变成是const A&,和that类型匹配;
当T为A时,std::remove_reference::type& 就变成是A&,和that类型不匹配,因为const引用不能赋值给非const引用。