如果我们有带通用引用参数的构造函数,如何声明复制构造函数?
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 [请看case 3和8],标准库中已经以某种方式解决了这个问题...但我无法理解stl的代码。
P.S. 这个问题与C++通用引用在构造函数和返回值优化中的应用有些关联。
P.P.S. 目前,我只是添加了额外的第一个参数Record(call_constructor, Refs&&... refs)
来进行显示调用。我可以手动检测是否只有一个参数且为Record
,然后将调用重定向到复制构造函数/参数构造函数,但...我不敢相信没有标准的方法来解决这个问题...