C++ - 函数模板(function template)右值引用参数 问题 及 解决
2013-11-28 15:12
891 查看
函数模板(function template)右值引用参数 问题 及 解决
本文地址: http://blog.csdn.net/caroline_wendy/article/details/17006205函数模板右值引用(&&)参数, 存在问题, 由于"&&"双引用符号的歧义性, 和引用崩溃(reference collapse)的原因;
如果不显示(explicit)指定和没有重载, 则函数使用右值引用参数, 既可以传递右值, 又可以传递左值;
传递右值时, 类型正常; 传递左值时, 由于绑定异常(binding exception), 使得T转为类型的引用;
如果是显示指定"int&", 则由于引用崩溃(reference collapse), 使得"int& &&"转换为"int&", 则未类型的引用;
解决方法可以是使用显示指定, 再使用重载参数;
代码如下:
/* * cppprimer.cpp * * Created on: 2013.11.28 * Author: Caroline */ #include <iostream> #include <typeinfo> template <typename T> void rvfnc (T&& val) { T t = val; ++t; if (val == t) std::cout << "rvfnc: this is lvalue." << std::endl; else std::cout << "rvfnc: this is rvalue." << std::endl; } template <typename T> void rvfnc (const T& val) { std::cout << "rvfnc(overload): this is lvalue." << std::endl; } int main (void) { int i(10); rvfnc(i); //左值 rvfnc(10); //右值 rvfnc<int&>(i); //如果包含重载则使用重载; 如果不包含, 则使用右值; return 0; }
输出:
rvfnc: this is lvalue. rvfnc: this is rvalue. rvfnc(overload): this is lvalue.
本文出自 “永不言弃” 博客,请务必保留此出处http://spikeking.blog.51cto.com/5252771/1387993
相关文章推荐
- C++ - 函数模板(function template)右值引用参数 问题 及 解决
- C++ - 函数模板(function template) 的 推进(forward) 问题 及 解决
- C++ - 函数模板(function template) 的 推进(forward) 问题 及 解决
- C++ - 函数模板(function template) 详解
- c++对象成员函数返回自身引用时出现的诡异问题及解决办法
- template学习之零值初始化及字符串常量作(function template argument)函数模版参数问题
- C++ Template中关于模板类的成员模板函数显示实例化的问题
- 函数模板中的参数引用问题
- C++11:利用模板简化重载右值引用参数的函数
- C++ - 成员函数(member function)模板(template) 详解 及 代码
- C++ - 成员函数(member function)模板(template) 详解 及 代码
- C++ - 函数模板(function template)返回值
- C++ - 函数模板(function template) 的 重载(overload) 详解 及 代码
- C++ - 函数模板(function template)返回值
- C++ - 函数模板(function template) 的 重载(overload) 详解 及 代码
- C++ - 函数模板定制(function template specialization) 详解 及 代码
- C++ - 函数模板定制(function template specialization) 详解 及 代码
- c++ 模板 迭代器 使用问题解决方法(too few template-parameter-lists)
- C++关于参数为const引用类型的函数调用参数成员函数的一个问题
- C++ 函数模板的特化(Function Template Specialization)