在Stroustrup的例子中,冒号在"return 1 : 2"中是什么意思?

In Stroustrup's example, what does the colon mean in "return 1 : 2"?

本文关键字:意思 是什么 return Stroustrup      更新时间:2023-10-16

我不明白冒号的一种特殊用法。

我在Bjarne Stroustrup的The C++ Programming Language一书中找到了它,第4版,第11.4.4节"Call and Return",第297页:

void g(double y)
{
  [&]{ f(y); }                                               // return type is void
  auto z1 = [=](int x){ return x+y; }                        // return type is double
  auto z2 = [=,y]{ if (y) return 1; else return 2; }         // error: body too complicated
                                                             // for return type deduction
  auto z3 =[y]() { return 1 : 2; }                           // return type is int
  auto z4 = [=,y]()−>int { if (y) return 1; else return 2; } // OK: explicit return type
}

令人困惑的冒号出现在语句 return 1 : 2 的第 7 行。我不知道会是什么。它不是标签或三元运算符。

它看起来像一个没有第一个成员(也没有?(的条件三元运算符,但在这种情况下,我不明白它如何在没有条件的情况下工作。

这是书中的一个错字。查看勘误表,了解 The C++ Programming Language 的第 2 次和第 3 次打印。示例必须如下所示:

auto z3 =[y]() { return (y) ? 1 : 2; }
在我看来

就像一个简单的错字。应该是:

auto z3 =[y]() { return y ? 1 : 2; }

请注意,由于 lambda 不带任何参数,因此括号是可选的。如果您愿意,可以改用它:

auto z3 =[y] { return y ? 1 : 2; }

return 1 : 2;是语法错误,它不是有效的代码。

正确的陈述更像是return (y) ? 1 : 2;