【C++17】新特性梳理

目錄

if init表達式

structual bindings

inline變量

std::string_view


 

if init表達式

C++17語言引入了一個新版本的if/switch語句形式,if (init; condition)switch (init; condition),即可以在ifswitch語句中直接對聲明變量並初始化,如下:

if(const auto it = myString.find("hello"); it != string::npos) {
    cout << it << " - Hello\n";
}
if(const auto it = myString.find("world"); it != string::npos) {
    cout << it << " - World\n";
}

如此一來,val僅在ifelse中可見,不會泄漏到其他作用域中去了。switch也支持initializatioin

 

structual bindings

  • struct/class的所有成員變量都是public
  • 任何返回tuple-like數據的地方: std::pairstd::tuplestd::array
  • 爲raw array的每個元素綁定一個名字

典型場景如下:

// 1 結構體和數組
struct MyStruct {
    int i;
    std::string s;
};
MyStruct getStruct() {
    return MyStruct{42, "hello"};
}
auto [id, val] = getStruct(); // id = i, val = s
//數組也適用
int arr[] = {1, 2};
auto [x, y] = arr;

// 2 簡化map的使用
for (const auto& elem: my_map) {
    std::cout << elem.first << ": " << elem.second << '\n';
}
for (const auto& [key, val]: my_map) {
    std::cout << key << ": " << val << '\n';
}

// 3 簡化tuple
tuple<int, string> func();
//before c++17
auto tup = func();
int i = get<0>(tup);
string s = get<1>(tup);
//or
int i;
string s;
std::tie(i, s) = func();
//c++17
auto [ i, s ] = func();

inline變量

c++11支持類體內初始化, 但是隻能是const成員, 非const只能放在class外

c++17後, 通過inline支持類體內初始化, 可以更好的支持head-only

struct MyClass {
    inline static const int sValue = 777;
};

std::string_view

推薦的使用方式:僅僅作爲函數參數

std::string調用sub_str()的時間複雜度是O(n);

sts::string_view調用sub_str()的時間複雜度是O(1);

參考:https://segmentfault.com/a/1190000018387368

 

總結

目前來看更多的是語法糖,尚需進一步的學習。

 

主要參考:https://tech.io/playgrounds/2205/7-features-of-c17-that-will-simplify-your-code/introductio

發佈了89 篇原創文章 · 獲贊 212 · 訪問量 47萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章