【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 篇原创文章 · 获赞 210 · 访问量 47万+

猜你喜欢

转载自blog.csdn.net/i_chaoren/article/details/104339467