为什么 lambda 转换为值为 true 的 bool? [英] Why does a lambda convert to a bool whose value is true?

查看:40
本文介绍了为什么 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.

这篇关于为什么 lambda 转换为值为 true 的 bool?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆