gpt4 book ai didi

c++ - bool lambda?

转载 作者:搜寻专家 更新时间:2023-10-30 23:58:48 25 4
gpt4 key购买 nike

这段代码怎么编译???

LIVE CODE

#include <iostream>


int main() {
auto lambda1 = []{};
auto lambda2 = []{};

if(lambda1 && lambda2) {
std::cout << "BOOLEAN LAMBDAS!!!" << std::endl;
}

if(lambda1 || lambda2) {
std::cout << "BOOLEAN LAMBDAS AGAIN FTW!!!" << std::endl;
}

bool b1 = lambda1;
bool b2 = lambda2;

std::cout << b1 << ", " << b2 << std::endl;
}

bool lambda! (或者 boolambdas,如果你愿意... *回避*)

这怎么行?这是另一个 GCC 错误吗?如果不是,这是标准吗?

最佳答案

原来是标准的!

如果你引用this answer [1]非捕获 lambda 可转换为函数指针。事实证明,函数指针本身就是指针,可以隐式转换为 bool!

4.12 Boolean conversions [conv.bool]

1 A prvalue of arithmetic, unscoped enumeration, pointer, or pointer to member type can be converted to a prvalue of type bool. A zero value, null pointer value, or null member pointer value is converted to false; any other value is converted to true. A prvalue of type std::nullptr_t can be converted to a prvalue of type bool; the resulting value is false.

为了证明转换为函数指针是所有这一切发生的原因,我尝试用捕获 lambda 来做同样的事情。然后生成“无法转换为 bool”错误。

LIVE CODE

int main() {
int i;
auto lambda = [i]{};

bool b = lambda;

if(lambda) {}
}

[1] 老实说,这给了我写这篇文章的想法。

关于c++ - bool lambda?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18889968/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com