【问题标题】:Does C++ guarantee the lambda unnamed class always has an "operator bool()" defined? [duplicate]C++ 是否保证 lambda 未命名类始终定义了“运算符 bool()”? [复制]
【发布时间】:2021-05-13 06:47:42
【问题描述】:
#include <type_traits>

int main()
{
    auto f = [] {};
    static_assert(std::is_same_v<decltype(!f), bool>); // ok

    f.operator bool(); // error: ‘struct main()::<lambda()>’ 
                       // has no member named ‘operator bool’
}

C++ 是否保证 lambda 未命名类始终定义了 operator bool()

【问题讨论】:

    标签: c++ lambda operator-overloading c++14 standards


    【解决方案1】:

    不,lambdas 没有 operator bool()

    !f 之所以有效,是因为没有捕获的 lambdas 可以转换为函数指针(它有一个转换运算符),然后可以转换为 bool,其值为 true,因为指针不为空。

    另一方面,

    int x;
    auto f = [x] {};
    !f; // not work; lambdas with captures can't convert to function pointer (and bool)
    
    猜你喜欢
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    • 2015-07-21
    • 2011-09-01
    • 2017-01-06
    • 2016-07-09
    • 2014-12-01
    • 2020-01-27
    相关资源
    最近更新 更多