C++17新特性(2) -- if/switch初始化(Init statement for if/switch)

1 Introduction

C++17语言引入了一个新版本的if/switch语句形式,if (init; condition)switch (init; condition),即可以在ifswitch语句中直接对声明变量并初始化。
if为例,在C++17之前,使用if我们可能会这样写:

{
    auto val = GetValue();
    if(condition(val))
    {
        // some codes if is true
    }
    else
    {
        // some codes if is false
    }
}

可以看出,val处于单独的一个scope中,即将val暴露在lf之外的作用于中。在C++17中可以这样写:

if(auto val = getValue(); condition(val))
{
    // some codes if is true
}
else
{
    // some codes if is false
}

如此一来,val仅在ifelse中可见,不会泄漏到其他作用域中去了。
注意:if中声明和初始化的变量valelse中也是成立的。

2 init-statement尝鲜

以下只是一些对该新特性的小小尝试,算是一些tricks

Case 1: 应对命名困难

这一部分主要是利用C++17init-statement特性来减少对新变量的命名,主要也就利用了在if/elseswitch中声明的变量具有更小的作用域这一特点。
假设在一个字符串中查找一个子串,我们可以这样写:

#include 
#include 

using namespace std;

int main()
{
    const string myString = "My hello world string";
    const auto it = myString.find("hello");
    if(it != string::npos)
    {
        cout << it << " - Hello\n";
    }
    // you have to make another name different from it.
    const auto it2 = myString.find("world");
    if(it2 != string::npos)
    {
        cout << it2 << " - World\n";
    }
    return 0;
}

我们可以声明并定义一个新变量it2,或者像下面一样将it用于单独的一个作用域:

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

但在C++17中,新的if-statement语法可以使得这样的作用域更简洁:

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";

前面说过,if语句中的变量在else中依然可见:

if(const auto it = myString.find("hello"); it != string::npos)
    cout << it << " - Hello\n";
else
    cout << it << " not found\n";

Case 2: if-initializer+structured binding

另外,新if-statement语法中也可以使用structured bindings

// better together: structured bindings + if initializer
if (auto [iter, succeeded] = mymap.insert(value); succeeded) {
    use(iter);  // ok
    // ...
}   // iter and succeeded are destroyed here

下面是一个完整的示例:

#include 
#include 
#include 

using namespace std;
using mySet = setstring,int>>;
int main()
{
    mySet set1;
    pair<string,int> itemsToAdd[3]{{"hello",1},{"world",1},{"world",2}};
    for(auto &p : itemsToAdd)
    {
        // if-initializer + structured binding
        if(const auto [iter,inserted] = set1.insert(p);inserted)
        {
            cout << "Value(" << iter->first << ", " << iter->second << ") was inserted\n";
        }
        else
        {
            cout << "Value(" << iter->first << ", " << iter->second << ") was not inserted\n";
        }
    }
    return 0;
}

Reference

[1]7 Features of C++17 that will simplify your code

你可能感兴趣的:(C++17新特性(2) -- if/switch初始化(Init statement for if/switch))