C++11系列學習之類型推導
auto類型推導
C++舊標準:
具有自動存儲的局部變量
auto int i = 0 //C++98
實際上我們一般不這樣寫,因為非static變量默認就是具有自動存儲的局部變量
C++11:
讓編譯器自動推斷出這個變量的類型,而不需要顯式指定類型
auto基本用法
演示:
auto x = 5 //x --> int auto pi = new auto(1) //pi --> int* const auto *v = &x, u = 6 //v --> const int* 、 u --> const int static auto y = 0.0 //y --> double int x = 0 auto * a = &x //a --> int* , auto為int auto b = &x //b --> int* , auto 為 int* auto c = x //c --> int& , auto為int auto d = c //d --> int , auto為int const auto e = x //e --> const int auto f = e //f --> int const auto& g = x //g --> const int& auto& h = g //h --> const int&
上面就是通常會出現(xiàn)的所有情況,其實可以類比模板參數(shù)自動推導
auto 不能用于函數(shù)參數(shù)
auto 推導規(guī)則
黃金法則:
- 當不聲明為指針或引用時,auto的推到結(jié)果和初始化表達式拋棄引用和cv限定符(cosnt 和 volatile,下同)后類型一致
- 當聲明為指針或引用時,auto的推到結(jié)果將保持初始化表達式的cv屬性
auto 的限制
- 不能用于函數(shù)參數(shù)
- 不支持非靜態(tài)成員變量的初始化
- main函數(shù)中auto不會被推導為數(shù)組類型,而是指針類型
auto 適用場景
場景一:for循環(huán)中用來遍歷容器
for(auto it = resultMap.begin(); it != resultMap.end(); ++i){ //do something }
場景二:用于不知道如何定義變量,多與泛型有關
class Foo{ public: static int get(void) { return 0; } }; class Bar{ public: static const char* get(void) { return "0"; } }; template<class A> void func(void) { auto val = A::get(); // ... }
decltype 類型推導
decltype( exp )
exp 表示一個表達式
從格式上來看,decltype像sizeof ,但其用來在編譯時推導出一個表達式的類型
decltype 基本用法
int x = 0 decltype(x) y = 1 //y -> int decltype(x + y) z = 0 //z -> int const int& i = x decltype(i) j = y //j -> const int & cosnt decltype(z) *p = &z //*p -> const int, p -> const int * decltype(z) * pi = &z //*pi -> int , pi -> int* decltype(pi) * pp = &pi //*pp -> int * ,pp -> int **
decltype和&結(jié)合的推導結(jié)果,與引用折疊規(guī)則有關,將在本系列后續(xù)中詳細講解
decltype 推導規(guī)則
黃金法則:
- exp是標識符、類訪問表達式,
decltype
(exp) 和exp的類型一致 - exp是寒素調(diào)用,
decltype
(exp) 和返回值 的類型一致 - 其他情況,若exp是個左值,則 ecltype(exp) 是exp類型的左值引用,否則和exp類型一致
decltype 適用場景
decltype適用于泛型相關
場景一:
標準庫中有些類型的定義
typedef decltype(nullptr) nullptr_t typedef decltype(sizeof(0)) size_t `
場景二:
通過變量表達式抽取變量類型實現(xiàn)簡寫
vector<int> v; decltype(v):value_type i = 0
場景三:
template<class ContainerT> class Foo { decltype(ContainerT().begin()) it_; public: void func(ContarinerT& container) { it_ = container.begin(); } // ... }
auto 和 decltype結(jié)合——返回類型后置
即通過兩個結(jié)合起來,使得語法更加靈活便捷
int & foo(int& i); float foo(float& f) template<typename T> auto fun(T& val) -> decltype(foo(val)) { return foo(val); }
小結(jié)
auto
和decltype
的出現(xiàn)不僅彌補了C++舊版標準的不足,也大大解放了開發(fā)人員的生產(chǎn)力,提升了效率。但是我們在使用的時候仍然需要注意,不能濫用,否則會出現(xiàn)我們期望得到的類型和最終程序的類型不一致,導致一些意想不到的BUG,給我維護增加了成本,適用和巧用才是正解!
到此這篇關于C++11系列學習之類型推導的文章就介紹到這了,更多相關C++11類型推導內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
VS2022連接sqlserver數(shù)據(jù)庫教程
本文主要介紹了VS2022連接sqlserver數(shù)據(jù)庫教程,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2022-07-07c語言中實現(xiàn)數(shù)組幾個數(shù)求次大值
這篇文章主要介紹了c語言中實現(xiàn)數(shù)組幾個數(shù)求次大值,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-12-12