为什么 lambda 转换为值为 true 的 bool?
#include <iostream>
void IsTrue(const bool value) {
if (value) {
std::cout << "value is True!
";
}
}
int main()
{
IsTrue([]() { ; /* some lambda */ });
return 0;
}
输出:
value is True!
为什么 lambda 在 GCC & 上评估为 true
铛?MSVC 无法构建它(无法将 lambda 转换为 bool).
Why does the lambda evaluate to true
on GCC & Clang? MSVC cannot build this (cannot convert lambda to bool).
这是一个编译器错误吗?或者标准的哪一段允许这样做?
Is it a compiler bug? Or which paragraph of the standard allows this?
推荐答案
C++14 标准 (§5.1.2) 说:
The C++14 standard (§5.1.2) says:
非泛型 lambda 表达式的闭包类型,没有lambda-capture 具有公共的非虚拟非显式 const 转换函数指向函数的指针 与 C++ 语言链接 (7.5)具有与闭包类型相同的参数和返回类型函数调用运算符.此转换函数返回的值应该是一个函数的地址,当被调用时,具有相同的效果如同调用闭包类型的函数调用操作符.
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
,因此您会得到所显示的结果.这是完全合法的.
Since a function pointer is implicitly convertible to bool
, you get the result you have shown. This is perfectly legal.
MSVC 不编译这个,因为这个转换运算符重载了不同的调用约定(__stdcall
、__cdecl
等).当为 x64
编译时,所有这些调用约定都没有使用,所以只有一个转换运算符,它编译得很好.
MSVC doesn't compile this because this conversion operator is overloaded with different calling conventions (__stdcall
, __cdecl
, etc).
When compiling for x64
all those calling conventions are not used, so there's just one conversion operator and it compiles fine.
相关文章