tow*_*120 5 c++ templates constructor c++11 c++14
如果我们有带有通用引用参数的构造函数,如何声明复制构造函数呢?
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;
}
Run Code Online (Sandbox Code Playgroud)
根据std::tuple http://en.cppreference.com/w/cpp/utility/tuple/tuple [查看案例3和8]的构造函数列表,这个问题在标准库中以某种方式解决了......但我无法通过stl的码.
PS问题与构造函数中的C++通用引用和返回值优化(rvo)有些相关
PPS目前,我刚Record(call_constructor, Refs&&... refs)为真正的EXPLICIT调用添加了额外的第一个参数.而且我可以手动检测我们是否只有一个参数,如果是Record,并且重定向调用复制ctr/param ctr,但....我不敢相信没有标准的方法...
在您的示例中,转发引用与 一起使用Record&。
因此,您可以添加额外的重载Record&(转发到复制构造函数):
Record(Record& other) : Record(static_cast<const Record&>(other)) {}
Run Code Online (Sandbox Code Playgroud)
或者在具有转发参考的那一个上使用 sfinae。