如何在C ++ 17中将“ else-if”与初始化程序一起使用?

use*_*764 -3 c++ lambda if-statement c++17

cpp参考https : //en.cppreference.com/w/cpp/language/if,看来我不能做到这一点:

if (cond)
{}
else if (init; cond)  // <<--- init not allowed with "else if"
{}
Run Code Online (Sandbox Code Playgroud)

我以一种相当愚蠢的方式解决了它:

if (cond)
{}
else if ([]() -> bool
{
    init;
    if (cond)
    {
        // Do something in the same scope as 'init'
        return true;
    }
    return false;
}())
{}
Run Code Online (Sandbox Code Playgroud)

我是否在这里缺少有关使用C ++ 17“正确”执行此操作的明显方法?

Som*_*ude 9

C ++没有“ else if”语句。相反,它是一个单独的else语句,后跟一个单独的if语句。

if (cond1)
{
    ...
}
else if (cond2)
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

相当于

if (cond1)
{
    ...
}
else
{
    if (cond2)
    {
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

因此使用else if (init; cond)应该是可以做到的。