【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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值