c++ - 右值和左值引用上的函数模板重载
问题描述
在关于“参考折叠”“在 r-values 和 l-values 上重载函数模板”的 c++ 入门中说:
template <typename T> void f(T&&); // binds to nonconst rvalues
template <typename T> void f(const T&); // lvalues and const rvalues
“与非模板函数一样,第一个版本将绑定到可修改的右值,第二个版本将绑定到左值或 const 右值。”
这个例子来自书中,但我认为有点不同:
第一个版本将绑定到可修改的右值和可修改的左值:
template <typename T>
void foo(T&& x)
{
cout << "foo(T &&)\n";
}
template <typename T>
void foo(T const& x)
{
cout << "foo(T const&)\n";
}
int main()
{
int i = 21;
int const ic = i;
foo(5); // foo(int&&)
foo(i); // foo(int&& ) -> new instantiation foo(int& x) --- here
foo(ic); // foo(int const&)
foo(std::move(i)); // foo(int&&)
foo(std::move(ic));// foo(&&) -> foo(int const&&)
cout << "\ndone!\n";
}
正如你所看到的,当我传递i
一个可修改的左值时,它foo(int&&)
被称为不是foo(int const&)
编译器将应用引用折叠产生以这种方式实例化一个版本的 foo :
void foo(int& x){}; // after reference collapsing
因此,仅当参数是常量 l 值或 const r 值时,才首选引用 const l 值的版本。(重载解析和功能匹配)
这就是我的想法。你怎么看?谢谢!
解决方案
推荐阅读
- spring-boot - Hystrix 断路器不选择 application.yml
- javascript - 按钮上的单击事件似乎没有触发
- python - 将 shapefile 转换为地理坐标
- python - TensorFlow 高效 Cyclegan 历史池
- swift - Swift SceneKit - 如何对齐节点的 y 轴以与某些 SCNVector3 重合?
- css - 材质 UI 选项卡内的功能未触发
- java - Android 将 PCM 和 MP3 合并为 AAC
- django - Django 版本 (2.0.7) urlpatterns 语法
- javascript - 如何在 JavaScript 中动态构建列表并在 HTML 中显示
- javascript - 检测页面底部以在反应中获取更多数据