如果我们也有带有通用引用参数的构造函数,又该如何声明复制构造函数?
http://coliru.stacked-crooked.com/a/4e0355d60297db57
struct Record{
template<class ...Refs>
explicit Record(Refs&&... refs){
cout << "param ctr" << endl;
}
Record(const Record& other){ // never called
cout << "copy ctr" << endl;
}
Record(Record&& other){ // never called
cout << "move ctr" << endl;
}
};
int main() {
Record rec("Hello");
Record rec2(rec); // do "param ctr"
return 0;
}
根据std::tuple
http://en.cppreference.com/w/cpp/utility/tuple/tuple的此构造函数列表[查看案例3和8],该问题以某种方式在标准库中得以解决...但是我无法通过stl的码。
PS问题与构造函数和返回值优化(rvo)中的C ++通用引用有些相关
PPS现在,我只是Record(call_constructor, Refs&&... refs)
为真正的EXPLICIT调用添加了其他第一个参数。而且我可以手动检测我们是否只有一个参数,如果是Record
,则可以重定向调用以复制ctr / param ctr,但是....我不敢相信没有标准的方法...
在您的示例中,转发参考与一起使用Record&
。
因此,您可以为添加一个额外的重载Record&
(以转发到构造函数):
Record(Record& other) : Record(static_cast<const Record&>(other)) {}
或在具有转发参考的那一个上使用sfinae。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句