#include <iostream>
void IsTrue(const bool value) {
if (value) {
std::cout << "value is True!\n";
}
}
int main()
{
IsTrue([]() { ; /* some lambda */ });
return 0;
}
输出:
value is True!
为什么 lambda 在 GCC 和 Clang 上评估为 true
? MSVC 无法构建它(无法将 lambda 转换为 bool)。
这是一个编译器错误吗?或者标准的哪一段允许这样做?
最佳答案
C++14 标准 (§5.1.2) 说:
The closure type for a non-generic lambda-expression with no lambda-capture has a public non-virtual non-explicit const conversion function to pointer to function with C++ language linkage (7.5) having the same parameter and return types as the closure type’s function call operator. The value returned by this conversion function shall be the address of a function that, when invoked, has the same effect as invoking the closure type’s function call operator.
由于函数指针可以隐式转换为 bool
,因此您会得到所显示的结果。这是完全合法的。
MSVC 不编译它,因为这个转换运算符重载了不同的调用约定(__stdcall
、__cdecl
等)。
当为 x64
编译时,所有这些调用约定都没有使用,所以只有一个转换运算符,它编译得很好。
关于c++ - 为什么 lambda 转换为值为 true 的 bool?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41720989/