c++11新特性--auto
2012-03-02 16:16
253 查看
auto 关键字
自动帮助推导类型auto i = 5 // i will be of type int int n=3; double pi=3.14; auto j=pi*n; // j will be of type double类型更难写的例子
// take a hypothetical Map of ( int and an map(int,int) ) map< int, map<int,int> > _Map; // see the verbose for defining a const iterator of this map map<int, map<int,int>>::const_iterator itr1 = _Map.begin(); // now with auto our life gets simplified const auto itr2 = _Map.begin();类型更难知晓的例子
template<class U, class V> void Somefunction(U u, V v) { ??? result = u*v; // now what would be the type of result ??? // with auto we leave the compiler to determine the type auto result = u*v; }新特性要点总结①我们可以使用valatile,pointer(*),reference(&),rvalue reference(&&) 来修饰auto
auto k = 5; auto* pK = new auto(k); auto** ppK = new auto(&k); const auto n = 6;②用auto声明的变量必须初始化
auto m; // m should be intialized③auto不能与其他类型组合连用
auto int p; // no way④函数和模板参数不能被声明为auto
void MyFunction(auto parameter){} // no auto as method argument template<auto T> // utter nonsense - not allowed void Fun(T t){}⑤定义在堆上的变量,使用了auto的表达式必须被初始化
int* p = new auto(0); //fine int* pp = new auto(); // should be initialized auto x = new auto(); // Hmmm ... no intializer auto* y = new auto(9); // Fine. Here y is a int* auto z = new auto(9); //Fine. Here z is a int* (It is not just an int)⑥以为auto是一个占位符,并不是一个他自己的类型,因此不能用于类型转换或其他一些操作,如sizeof和typeid
int value = 123; auto x2 = (auto)value; // no casting using auto auto x3 = static_cast<auto>(value); // same as above⑦定义在一个auto序列的变量必须始终推导成同一类型
auto x1 = 5, x2 = 5.0, x3='r'; // This is too much....we cannot combine like this⑧auto不能自动推导成CV-qualifiers(constant & volatile qualifiers),除非被声明为引用类型
const int i = 99;auto j = i; // j is int, rather than const intj = 100 // Fine. As j is not constant// Now let us try to have referenceauto& k = i; // Now k is const int&k = 100; // Error. k is constant// Similarly with volatile qualifer⑨auto会退化成指向数组的指针,除非被声明为引用
int a[9];auto j = a;cout<<typeid(j).name()<<endl; // This will print int*auto& k = a;cout<<typeid(k).name()<<endl; // This will print int [9]
引自codeproject,仅供个人参考
相关文章推荐
- 转载C++11新特性auto
- C++11新特性之auto&decltype
- 【C++11】新特性——auto的使用
- C++11新特性——auto和decltype类型推导
- C++11新特性:类型别名,auto类型,decltype类型
- C++11新特性之一:auto
- C++11特性--auto,decltype,返回类型后置,using=,nullptr
- c++11 新特性之 auto关键字
- C++学习之路(38)---C++11特性:auto关键字
- 【C++11】新特性——auto的使用
- 【C++11新特性】 auto关键字
- 【C++11】新特性——auto的使用
- C++11新特性— auto 和 decltype 区别和联系
- 【C++11】新特性——auto的使用 (@huang_xw)
- 【C++11】新特性——auto的使用
- 【C++11新特性】auto关键字
- c++11新特性 auto的使用
- c++11的一些特性auto和范围for循环
- C++11常用特性学习-易学易用新特性(>>/auto/decltype/范围的for)
- C++11新特性,利用auto和std::chrono获取系统时间的方法