uj2*_*uj2 6 c++ templates type-inference reference rvalue
考虑这样一种情况:函数模板需要转发参数,同时保持它的左值,以防它是非const左值,但它本身与参数实际上是无关的,如:
template <typename T>
void target(T&) {
cout << "non-const lvalue";
}
template <typename T>
void target(const T&) {
cout << "const lvalue or rvalue";
}
template <typename T>
void forward(T& x) {
target(x);
}
Run Code Online (Sandbox Code Playgroud)
何时x
是rvalue,而不是T
推导为常量类型,它会给出错误:
int x = 0;
const int y = 0;
forward(x); // T = int
forward(y); // T = const int
forward(0); // Hopefully, T = const int, but actually an error
forward<const int>(0); // Works, T = const int
Run Code Online (Sandbox Code Playgroud)
似乎对于forward
处理rvalues(不需要显式模板参数),需要有一个forward(const T&)
重载,即使它的主体是完全重复的.
有没有办法避免这种重复?
这是一个已知问题,也是C++ 0x中rvalue引用的目的.这个问题在C++ 03中没有通用的解决方案.
有一些古老的历史原因,为什么会发生这种情况,这是非常无意义的.我记得曾经问过一次,答案让我非常沮丧.