c++ - 将 lambda 分配给 std::function

标签 c++ lambda c++11 implicit-conversion std-function

当推断的返回类型为 std::nullptr_t 时,为什么允许第二次赋值?对于函数指针,这是被禁止的。

为什么第二个 lambda 没有运行?

#include <cstdio>
#include <functional>

int main()
{
    std::function<void* ()> f;

    f = []() -> void* {
        printf ("runs\n");
        return nullptr;
    };
    f();

    f = []() {
        printf ("doesn't run\n");
        return nullptr; // -> std::nullptr_t
    };
    f();

    return 0;
}

最佳答案

std::function 允许您存储任何内容,只要以下内容适用于您提供的签名:

  • 所有参数类型都可以隐式转换为存储的可调用实体的参数类型,并且
  • 存储的可调用实体的返回类型可以隐式转换为签名的返回类型

std::nullptr_t 可隐式转换为任何指针类型并产生该指针类型的空指针值。

请注意,您的代码实际上不是有效的 C++11,因为您不仅在第二个 lambda 中有 return expr;,因此不会发生返回类型推导。 GCC(和 Clang、IIRC)将其作为扩展来实现,因为它将在某个时候成为标准的一部分。

关于c++ - 将 lambda 分配给 std::function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13212617/

相关文章:

c++ - 最大字符限制条件和最小字符放置条件

C++ 对结构 vector 进行排序

C++ extern 未解析的符号错误 LNK2001

java - 如何在 Lambda 中将具有一个参数的方法引用到具有两个参数的目标?

c# - 使用 Enumerable.Range() 填充字典时出现问题

c++ - 使用 Visual Studio Code Ubuntu 调试 c++ 代码

c++ long double 精确打印所有数字

c++ - 如何在不使用全局变量的情况下访问 lambda 中的变量?

c++ - "I just can not understand DR 712"的延续

c++ - 在给定范围内查找对值