c++ - 为什么 lambda 转换为值为 true 的 bool?

标签 c++ lambda boolean language-lawyer

#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/

相关文章:

c++ - 对两个构造函数使用 'this' 指针

c++ - 是否有 "simple"方法让 ld 输出 demangle 函数名称?

java - Java中Enum对应的BiFunctional函数如何实现?

java - OnKeyListener 仅在模拟器中工作

c++ - 如何在cout中添加变量?

c++ - 将对象移动到不同的线程

c# - 填充列表上的 lambda 表达式

c# - 使用 lambda 构建器模式

java - 如何将 else false 添加到 boolean 方法

objective-c - 在 nsuserdefaults 中保存 bool