【问题标题】:How could c++ std::bind return value assigned to std::function?c++ std::bind 如何返回分配给 std::function 的值?
【发布时间】:2020-05-07 03:19:59
【问题描述】:

考虑下面的一些简单代码:

int f1(int a) {
  std::cout << a << std::endl;
}

int main (int agrc, char* argv[]) {
  std::function<int(int)> f = std::bind(&f1, std::placeholders::_1);
  f(123);

  return 0;
}

我已经阅读了一些关于 std::function 和 std::bind 的文档,但仍然不明白它是如何工作的。
编译器显示 std::bind 的调用返回一个 _Bind_helper 类型的对象,但是,我没有看到 std::function 类具有输入类型为 _Bind_helper 的构造函数,那么 std::function xxx = std 如何::绑定 xxx 工作?

【问题讨论】:

  • std::function 有一个构造函数模板,采用任何可调用的仿函数类型。
  • 顺便提一下:这里没有必要使用std::bindstd::function&lt;int(int)&gt; f(f1); 将做完全相同的事情,而没有 std::bind 增加的开销。

标签: c++ function c++11 stl bind


【解决方案1】:

我没有看到std::function类有一个输入类型为_Bind_helper的构造函数,那么std::function xxx = std::bind xxx是怎么工作的呢?

它确实有这样的构造函数。就是这个:

template< class F >
function( F f );

请注意,仅当(推导的)模板参数是 Callable 时,此转换构造函数才参与重载解析 - std::bind 的返回类型是。

【讨论】:

    【解决方案2】:

    根据ccpreference.com

    类模板std::function是一个通用的多态函数 包装。 std::function 的实例可以存储、复制和调用任何 可调用目标 -- 函数、lambda 表达式、绑定表达式或 其他函数对象,以及指向成员函数的指针和 指向数据成员的指针。

    存储的可调用对象被称为 std::function 的目标。如果一个 std::function 不包含目标,称为空。调用 空 std::function 的目标导致std::bad_function_call 抛出异常。

    std::function 满足 CopyConstructible 和 可复制。

    std::function 基本上是一个可调用对象的包装器。它被称为类型擦除对象 - 它擦除操作的细节以提供通用接口。

    你的std::bind 表达

    std::bind(&f1, std::placeholders::_1)
    

    生成一个函数对象,该对象使用您在占位符中提供的参数调用函数f1,返回类型为int。因此,您可以将其分配给具有相同签名的函数对象:

    std::function<int(int)>
    

    它使用带有可调用对象的构造函数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-23
      • 2012-10-29
      • 2016-12-20
      相关资源
      最近更新 更多