如果你有这个功能
template<typename T> f(T&);然后试着用下面这样的rvalue来调用它
f(1);为什么T不能被推导为const int,使参数成为const int&,从而可以绑定到rvalue?
发布于 2010-08-29 02:22:23
这是在recent C++0x forwarding question中链接的the document中提到的一个潜在解决方案。
它将工作得相当好,但它破坏了现有的代码。考虑一下(直接从文档中):
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
}或
// 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]);
}这也无法转发值类别(左值或右值),这在C++03中不是什么大问题。但由于此修复只能在C++0x期间完成,因此在转发时,我们实际上会将自己排除在右值引用之外(这是一件坏事)。我们应该争取一个更好的解决方案。
发布于 2010-08-29 02:10:13
确实如此,但前提是您必须声明f以T const &作为参数。
template <typename T> void f(T &);
template <typename T> void g(T const &);
void x() { f(1); } // error: invalid initialization of non-const reference
void y() { g(1); } // no error如果同时声明f(T &)和f(T const &),它将选择const限定的参数:
template <typename T> void f(T &);
template <typename T> void f(T const &);
void x() { f(1); } // no error, calls f(T const &)现在,您可能会问“在第一个示例中,当它本可以生成类型为const int的临时类型并编译代码时,为什么要为对f的调用生成类型为int的临时类型?”我给你的最好答案是,当参数不是整数常量时,这将与重载解析行为不一致。
https://stackoverflow.com/questions/3591832
复制相似问题