【发布时间】:2015-11-24 01:41:46
【问题描述】:
如果我们有带有通用引用参数的构造函数,如何声明复制构造函数?
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::tuplehttp://en.cppreference.com/w/cpp/utility/tuple/tuple的构造函数列表[看案例3和8]这个问题在标准库中以某种方式解决了......但我无法通过stl的代码。
附:与C++ universal reference in constructor and return value optimization (rvo)有些相关的问题
附言现在,我只是为真正的显式调用添加了额外的第一个参数Record(call_constructor, Refs&&... refs)。而且我可以手动检测我们是否只有一个参数,如果它是Record,然后重定向调用以复制 ctr/param ctr,但是....我不敢相信没有标准的方法...
【问题讨论】:
-
我无法写出完整的答案,但这应该对您有所帮助akrzemi1.wordpress.com/2013/10/10/too-perfect-forwarding 基本思想是使用 SFINAE。
-
@DanielJour 这有点类似于我的 P.P.S.部分,但是谢谢,我很高兴知道这是已知问题...
-
为了将来验证这个问题,需要指出的是,universal reference 将正式称为forwarding reference。可以在here找到提案。
标签: c++ templates c++11 constructor c++14