C++11:型別推導auto
阿新 • • 發佈:2019-02-08
原文:http://blog.csdn.net/huang_xw/article/details/8760403
C++11中引入的auto主要有兩種用途:自動型別推斷和返回值佔位。auto在C++98中的標識臨時變數的語義,由於使用極少且多餘,在C++11中已被刪除。前後兩個標準的auto,完全是兩個概念。
1. 自動型別推斷
auto自動型別推斷,用於從初始化表示式中推斷出變數的資料型別。通過auto的自動型別推斷,可以大大簡化我們的程式設計工作。下面是一些使用auto的例子。[cpp] view plaincopyprint?
- #include <vector>
-
#include <map>
- usingnamespace std;
- int main(int argc, char *argv[], char *env[])
- {
- // auto a; // 錯誤,沒有初始化表示式,無法推斷出a的型別
- // auto int a = 10; // 錯誤,auto臨時變數的語義在C++11中已不存在, 這是舊標準的用法。
- // 1. 自動幫助推導型別
- auto a = 10;
- auto c = 'A';
- auto s("hello");
- // 2. 型別冗長
-
map<int, map<
- map<int, map<int,int>>::const_iterator itr1 = map_.begin();
- const auto itr2 = map_.begin();
- auto ptr = []()
- {
- std::cout << "hello world" << std::endl;
- };
- return 0;
- };
- // 3. 使用模板技術時,如果某個變數的型別依賴於模板引數,
-
// 不使用auto將很難確定變數的型別(使用auto後,將由編譯器自動進行確定)。
- template <class T, class U>
- void Multiply(T t, U u)
- {
- auto v = t * u;
- }
2. 返回值佔位
[cpp] view
plaincopyprint?
- template <typename T1, typename T2>
- auto compose(T1 t1, T2 t2) -> decltype(t1 + t2)
- {
- return t1+t2;
- }
- auto v = compose(2, 3.14); // v's type is double
3.使用注意事項
①我們可以使用valatile,pointer(*),reference(&),rvalue reference(&&) 來修飾auto[cpp] view plaincopyprint?
- auto k = 5;
- auto* pK = new auto(k);
- auto** ppK = new auto(&k);
- const auto n = 6;
[cpp] view plaincopyprint?
- auto m; // m should be intialized
[cpp] view plaincopyprint?
- auto int p; // 這是舊auto的做法。
[cpp] view plaincopyprint?
- void MyFunction(auto parameter){} // no auto as method argument
- template<auto T> // utter nonsense - not allowed
- void Fun(T t){}
[cpp] view plaincopyprint?
- 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)
[cpp] view plaincopyprint?
- int value = 123;
- auto x2 = (auto)value; // no casting using auto
- auto x3 = static_cast<auto>(value); // same as above
[cpp] view plaincopyprint?
- auto x1 = 5, x2 = 5.0, x3='r'; // This is too much....we cannot combine like this
[cpp] view plaincopyprint?
- constint i = 99;
- auto j = i; // j is int, rather than const int
- j = 100 // Fine. As j is not constant
- // Now let us try to have reference
- auto& k = i; // Now k is const int&
- k = 100; // Error. k is constant
- // Similarly with volatile qualifer
[cpp] view plaincopyprint?
- 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]