C++ 11 auto & decltype
来源:互联网 发布:windows http代理软件 编辑:程序博客网 时间:2024/05/22 15:22
C++ 11中引入的auto主要有两种用途:自动类型推断和返回值占位。auto在C++ 98中的标识临时变量的语义,
由于使用极少且多余,在C++ 11中已被删除。auto自动类型推断,用于从初始化表达式中推断出变量的数据
类型。通过auto的自动类型推断,可以大大简化我们的编程工作。下面是一些使用auto的例子。
auto a; // 错误,没有初始化表达式,无法推断出a的类型auto int a = 10; // 错误,auto临时变量的语义在C++ 11中已不存在auto a = 10;auto c = 'A';auto s("hello");vector<int> vctTemp;auto it = vctTemp.begin();auto ptr = [](){ cout << "hello world" << endl; };另外,在使用模板技术时,如果某个变量的类型依赖于模板参数,不使用auto将很难确定变量的类型(使用
auto后,将由编译器自动进行确定)。下面是一个具体的例子。
template <class T, class U>void Multiply(T t, U u){auto v = t*u;}auto返回值占位,主要与decltype配合使用,用于返回值类型后置时的占位。
template <class T, class U>auto Multiply(T t, U u)->decltype(t*u){typedef decltype(t*u) NewType;NewType *pResult = new NewType(t*u);return *pResult;}至于为什么需要将返回值类型后置,这里简单说明一下。如果没有后置,则函数声明为decltype(t*u)
Multiply(T t, U u),但此时模板参数t和u还未声明,编译无法通过。另外,如果非要使用返回值类
型前置的形式,也可以将函数声明为decltype((*(T *)0)*(*(U *)0))Multiply(T t, U u),但这种形
式比较晦涩难懂,因此不推荐采用。
0 0
- C语言11中的auto和decltype
- C++ 11 auto & decltype
- C++ 11 auto & decltype
- C++ 11 auto & decltype
- C++11 auto&decltype
- C++11 auto 和decltype
- C++11 auto and decltype
- C++11 auto 和 decltype
- C++11 decltype 和auto
- C++primer---constexpr、类型别名、auto、decltype
- C++11学习:auto和decltype
- c++11新特性---auto 与 decltype
- C++11的auto和decltype关键字
- C++11 auto和decltype推导规则
- C++11学习笔记3---auto&decltype
- C++11之auto、decltype关键字
- C++11的auto和decltype关键字
- C++11的auto与decltype
- Echart获取后台数据渲染到map,bar
- java反射及动态代理
- Smarty之单模板多缓存,删缓存,不缓存
- iOS设计模式——单例模式
- android 通知的使用(Notification)
- C++ 11 auto & decltype
- 使用Spring 时出现InvocationTargetException
- jQuery 遍历- 关于closest() 的方法介绍以及与parents()的方法区别分析
- TatukGIS Editor使用教程:位置显示和三角测量
- 3D数学--矩阵知识
- lombok造成的StackOverflowError
- 分布式发布订阅消息系统 Kafka 架构设计 - 目前见到的最好的Kafka中文文章
- 概率算法(算法分析与设计)
- Learning HBase中文版——互动出版网