问题描述
此代码如何编译???
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?
推荐答案
原来是标准的!
如果您引用 ,非 - 捕获 lambdas可转换为函数指针。再次证明,作为指针本身的函数指针可隐式转换为 bool
!
If you refer to this answer, non-capturing lambdas are convertible to function pointers. And it turns out again that function pointers, being pointers themselves, are implicitly convertible to bool
!
为了证明转换为函数指针是什么使得所有这一切发生,我试图做同样的事情捕获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) {}
}
这篇关于布尔lambda?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!