布尔lambda? [英] Boolean lambdas?
问题描述
此代码如何编译???
How come this code compiles???
#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;
}
Boolean lambdas! (或boolambdas,如果你会... *害羞*)
Boolean lambdas! (Or boolambdas, if you will... *shies away*)
这是如何工作的?这是另一个GCC错误吗?如果没有,是这个标准吗?
How come this works? Is this another GCC bug? If not, is this standard?
推荐答案
原来是标准的!
如果您引用此答案 [1] ,非 - 捕获 lambdas可转换为函数指针。再次证明,作为指针本身的函数指针可隐式转换为 bool
!
If you refer to this answer[1], non-capturing lambdas are convertible to function pointers. And it turns out again that function pointers, being pointers themselves, are implicitly convertible to bool
!
4.12布尔转换[conv.bool]
1 算术,无范围枚举,指针或指向成员类型的指针可以转换为bool类型的
prvalue。零值,空指针值或空成员指针值将转换为false;
任何其他值都将转换为true。可以将类型std :: nullptr_t的prvalue转换为
类型的prval值bool;结果值为false。
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.
为了证明转换为函数指针是什么使得所有这一切发生,我试图做同样的事情捕获lambdas。然后无法转换为 bool
错误。
To give a supporting proof that the conversion to function pointer is what makes all of this happen, I've tried doing the same thing with capturing lambdas. Then "can't convert to bool
" errors are generated.
int main() {
int i;
auto lambda = [i]{};
bool b = lambda;
if(lambda) {}
}
[1] 老实说,给了我写这个的想法。
这篇关于布尔lambda?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!