Pup*_*ppy 24 c++ forwarding c++03
如果你有这个功能
template<typename T> f(T&);
Run Code Online (Sandbox Code Playgroud)
然后尝试调用它,让我们说一个rvalue就好
f(1);
Run Code Online (Sandbox Code Playgroud)
为什么T不能被推导为const int,使得参数成为一个const int&因而可以绑定到一个rvalue?
GMa*_*ckG 24
这是我在最近的C++ 0x转发问题中链接的文档中的潜在解决方案.
它可以很好地工作,但它打破了现有的代码.考虑(直接来自文档):
template<class A1> void f(A1 & a1)
{
std::cout << 1 << std::endl;
}
void f(long const &)
{
std::cout << 2 << std::endl;
}
int main()
{
f(5); // prints 2 under the current rules, 1 after the change
int const n(5);
f(n); // 1 in both cases
}
Run Code Online (Sandbox Code Playgroud)
要么
// helper function in a header
template<class T> void something(T & t) // #1
{
t.something();
}
// source
#include <vector>
void something(bool) // #2
{
}
int main()
{
std::vector<bool> v(5);
// resolves to #2 under the current rules, #1 after the change
something(v[0]);
}
Run Code Online (Sandbox Code Playgroud)
这也无法转发值类别(左值或右值),这在C++ 03中没有太大问题.但由于此修复只能在C++ 0x期间完成,因此我们在转发时会有效地将自己从rvalue引用中关闭(这是一件坏事).我们应该努力寻求更好的解决方案.