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

查看:99
本文介绍了为什么将lambda转换为值为true的布尔值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#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和ACC上的评估结果为 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 ++语言链接的指向函数的指针具有与封闭类型相同的参数和返回类型函数调用运算符.此转换函数返回的值当被调用时具有相同功能的函数的地址就像调用闭合类型的函数调用运算符一样.

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的布尔值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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