在A Brief Introduction to Rvalue References中,提出了完美转发作为将 rvalue 5 转发到具有非常量引用参数的构造函数的理想解决方案。
但:
#include <memory>
#include <iostream>
#include <utility>
template <class T, class A1>
std::shared_ptr<T> factory(A1&& a1) {
return std::shared_ptr<T>(new T(std::forward<A1>(a1)));
}
class X {
public:
X(int& i){
std::cout<<"X("<<i<<")\n";
}
};
int main() {
std::shared_ptr<X> p = factory<X>(5);
}
XCode 4.2 ans G++ 4.6.1 with 失败no known conversion from int to int&
,而:
template <class T, class A1>
std::shared_ptr<T> factory(A1&& a1) {
return std::shared_ptr<T>(new T(/*no forwarding*/a1));
}
编译。我做错了什么?