C++11 理解 (一) 之 auto与decltype的运用
2013-08-21 13:27
288 查看
类型推导与auto关键字
在标准C/C++,使用变量必须明确的指出其类型(强类型)。然而随着模板类型的出现以及模版元编程的技巧,指定类型,特别是函数定义明确的指定返回类型,就不容易表示。在这样的情况下,将中间结果存储与变量是一件困难的事情,可能会需要知道特定的元编程程序库的内部情况。C++11提供了两种方法缓解上述所遇到的困难。首先被有明确初始化的变量可以使用auto关键字。这会依据该初始化式的具体类型产生变量。示例:
auto someStrangeCallableType = boost::bind(&SomeFunction, _2, _1, someObject); |
auto otherVariable =5; |
otherVariable 的类型同样也是明确定义的,但用户很容易就能判断。它是个int(默认整数类型)。
除此之外,C++11还定义了 decltype 能够被用来在编译器决定一个表达式的类型。举例:
int someInt; decltype(someInt) otherIntegerVariable =5; |
auto 对于减少冗赘的代码也很有用。举例而言,程序员不用写像下面这样:
for(vector<int>::const_iterator itr = myvec.begin(); itr != myvec.end();++itr) |
for(auto itr = myvec.begin(); itr != myvec.end();++itr) |
decltype 所表示的类型可以和 auto 推导出来的不同。
#include <vector> int main(){ const std::vector<int> v(1); auto a = v[0];// a 为 int 类型 decltype(v[0]) b =0;// b 为 const int& 类型,即std::vector<int>::operator[](size_type)const 的返回类型 auto c =0;// c 为 int 类型 auto d = c;// d 为 int 类型 decltype(c) e;// e 为 int 类型,c 实体的类型 decltype((c)) f = e;// f 为 int& 类型,因为(c)是左值 decltype(0) g;// g为int类型,因为0是右值 return 0; } |
相关文章推荐
- C++11标准 类型别名 auto decltype 范围for循环等测试
- C++11之auto和decltype
- c++11 学习及测试(auto,decltype,range for...)
- [C++]高效使用c++11--理解auto类型推导
- C++11:使用 auto/decltype/result_of使代码可读易维护
- c++11——auto,decltype类型推导
- C++11新特性— auto 和 decltype 区别和联系
- c++11新特性---auto 与 decltype
- C++11 auto&decltype
- C++11中auto、decltype等关键字不能在codeblacks的GNU编译器识别通过的问题的解决
- C++11中auto 关键字、nullptr关键字和decltype关键字
- C++11中auto、decltype等关键字不能在codeblacks的GNU编译器识别通过的问题的解决
- C++11特性(7):auto、decltype(自匹配类型)
- C++11系列-改进的类型推导:auto、decltype和新的函数语法
- C++11的auto与decltype
- 【C++】C++11的auto和decltype关键字
- c++11新特性--decltype auto
- C++11特性--auto,decltype,返回类型后置,using=,nullptr
- C++11系列-改进的类型推导:auto、decltype和新的函数语法
- C++Primer第五版【学习笔记】——auto,decltype【C++11】