您好,登錄后才能下訂單哦!
今天就跟大家聊聊有關(guān)C++中怎么使用auto避免多余的類型名重復(fù),可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。
Simple repetition is tedious and error-prone.
簡(jiǎn)單的重復(fù)多余且易錯(cuò)。
When you use auto, the name of the declared entity is in a fixed position in the declaration, increasing readability.
當(dāng)你使用auto的時(shí)候,被定義實(shí)體的名稱會(huì)出現(xiàn)在固定的位置,這樣可以增加可讀性。
In a template function declaration the return type can be a member type.
在模板函數(shù)定義中,返回值可以是成員類型。
Consider:
考慮以下代碼:
auto p = v.begin(); // vector<int>::iterator
auto h = t.future();
auto q = make_unique<int[]>(s);
auto f = [](int x){ return x + 10; };
In each case, we save writing a longish, hard-to-remember type that the compiler already knows but a programmer could get wrong.
無(wú)論哪種情況,我們都不必編寫(xiě)又長(zhǎng)、類型又難記的類型信息。其實(shí)這些信息編譯器已經(jīng)知道,但程序員還是會(huì)弄錯(cuò)。
Example(示例)
template<class T>
auto Container<T>::first() -> Iterator; // Container<T>::Iterator
Avoid auto for initializer lists and in cases where you know exactly which type you want and where an initializer might require conversion.
對(duì)于你確切地知道所需類型但初始化器可能需要轉(zhuǎn)換的情況,應(yīng)避免為初始化列表使用auto。
Example(示例)
auto lst = { 1, 2, 3 }; // lst is an initializer list
auto x{1}; // x is an int (in C++17; initializer_list in C++11)
When concepts become available, we can (and should) be more specific about the type we are deducing:
在concepts可以之后,我們可以(也應(yīng)該)更加明確我們推斷的類型。
// ...
ForwardIterator p = algo(x, y, z);
示例(C++17)
auto [ quotient, remainder ] = div(123456, 73); // break out the members of the div_t result
Flag redundant repetition of type names in a declaration.
標(biāo)記在聲明時(shí)發(fā)生的多余的類型名稱重復(fù)。
看完上述內(nèi)容,你們對(duì)C++中怎么使用auto避免多余的類型名重復(fù)有進(jìn)一步的了解嗎?如果還想了解更多知識(shí)或者相關(guān)內(nèi)容,請(qǐng)關(guān)注億速云行業(yè)資訊頻道,感謝大家的支持。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。