我一直在切换模板工厂函数以使用(并理解)std::forward 来支持右值和移动语义。我通常用于模板类的样板工厂函数总是将参数标记为 const:
#include <iostream>
#include <utility>
template<typename T, typename U>
struct MyPair{
MyPair(const T& t, const U& u):t(t),u(u){};
T t;
U u;
};
template<typename T, typename U>
std::ostream& operator<<(std::ostream& os, const MyPair<T,U>& pair){
os << "(" << pair.t << ")=>" << pair.u;
return os;
}
template<typename T, typename U>
MyPair<T,U> MakeMyPair(const T& t, const U& u){
return MyPair<T,U>(t,u);
}
using namespace std;
int main(int argc, char *argv[]) {
auto no_forward = MakeMyPair(num, num);
std::cout << no_forward << std::endl;
auto no_forward2 = MakeMyPair(100, false);
std::cout << no_forward2 << std::endl;
}
按预期编译。最初我将 MakeMyPair 转换为也将参数作为 const 传递,但这不会在我的 Mac 上使用 XCode 4.6 编译:
//$ clang --version
//Apple LLVM version 4.2 (clang-425.0.24) (based on LLVM 3.2svn)
//Target: x86_64-apple-darwin12.2.0
//Thread model: posix
template<typename T, typename U>
MyPair<T,U> MakeMyPair_Forward(const T&& t, const U&& u){
return MyPair<T,U>(std::forward<const T>(t),std::forward<const U>(u));
}
int main(int argc, char *argv[]) {
int num = 37;
auto anotherPair = MakeMyPair_Forward(num, true); //This won't work
auto allRvalues = MakeMyPair_Forward(73, false); //will compile
std::cout << allRvalues << std::endl;
}
没有匹配函数调用“MakeMyPair_Forward”候选函数 [with T = int, U = bool] 不可行:第一个参数没有从“int”到“const int &&”的已知转换
这从http://en.cppreference.com/w/cpp/utility/forward是有道理的,其中状态 const 是推导出来的,我正在传递左值。
- 如果对 wrapper() 的调用传递了一个右值 std::string,则 T 被推导出为 std::string(不是 std::string&、const std::string& 或 std::string&&),并且 std::forward 确保将右值引用传递给 foo。
- 如果对 wrapper() 的调用传递了一个 const 左值 std::string,则将 T 推导出为 const std::string&,而 std::forward 确保将一个 const 左值引用传递给 foo。
- 如果对 wrapper() 的调用传递了一个非常量左值 std::string,则 T 被推导出为 std::string&,并且 std::forward 确保将非常量左值引用传递给 foo。
使用右值和左值删除 const 可以按我的意愿工作。只有将右值作为类型传递才能与 MakeMyPair_Forward 参数上的 const 一起使用。
//This works for rvalues and lvalues
template<typename T, typename U>
MyPair<T,U> MakeMyPair_Forward(T&& t, U&& u){
return MyPair<T,U>(std::forward<const T>(t),std::forward<const U>(u));
}
所以,问题。作为参数传递时将右值引用标记为 const 是否有意义?这不像我可以更改右值,这只是暂时的。在完成和修复我的代码之后,我对它使用 const 编译感到有点惊讶。为什么要将右值参数标记为 const?重点是只提供一个接受右值的 API 吗?如果是这样,您不会使用类型特征来防止左值引用吗?https://stackoverflow.com/a/7863645/620304
谢谢。