简体   繁体   English

std :: function和std :: bind行为

[英]std::function and std::bind behavior

I have this code: 我有这个代码:

#include <iostream>
#include <functional>
#include <vector>

void fun()
{
    std::cout<<"fun";
}

void gun(int)
{
    std::cout<<"gun";
}

int main()
{
    std::vector<std::function<void(int)>> vec;

    vec.push_back(std::bind(fun));
    vec.push_back(gun);

    vec[0](1);
    vec[1](2);
}

Can you please explain how it's possible for std::bind to return std::function<void(int)> when binding void() function? 你能解释一下std::bind在绑定void()函数时如何返回std::function<void(int)>

How it's possible to call void() function by using void(int) functor? 如何使用void(int)函数调用void()函数?

The signature passed as the template argument for function only determines how many place holders ( _1 ) will be bound, and as what types. 作为function的模板参数传递的签名仅确定将绑定多少个占位符( _1 )以及哪些类型。

The invocation of the actual function only uses the number of arguments actually required by the bound function. 实际函数的调用仅使用绑定函数实际需要的参数数量。 In effect, the superfluous parameter is ignored. 实际上,忽略了多余的参数。

Another, more enlightening (?) example, looking at this from the other side: 另一个更具启发性(?)的例子,从另一方面看这个:

#include <iostream>
#include <functional>

void gun(int i)
{
    std::cout<<"gun("<<i<<")";
}

int main()
{
    using namespace std::placeholders;
    std::bind(gun, _5)("ignore", 3, "and", 4, 43);
}

Prints 打印

gun(43)

How it's possible to call void() function by using void(int) functor? 如何使用void(int)函数调用void()函数?

std::bind(fun) does not return a void() function, it returns a call wrapper of unspecified type. std::bind(fun)不返回void()函数,它返回一个未指定类型的调用包装器。

The usual way to invoke that call wrapper would be with zero arguments, but in most implementations of bind() that type can be called with zero or more arguments and the additional arguments will be ignored (ie not passed to the target function) 调用该调用包装器的常用方法是使用零参数,但在大多数bind()实现中,可以使用零个或多个参数调用该类型,并忽略其他参数(即不传递给目标函数)

More generally, for a function F taking N arguments, bind(F) returns a call wrapper that can be called with N or more arguments. 更一般地,对于带有N参数的函数Fbind(F)返回一个可以用N或更多个参数调用的调用包装器。 If you bind arguments or use placeholders then it will alter the minimum number of arguments needed to invoke the call wrapper. 如果绑定参数或使用占位符,则它将更改调用调用包装器所需的最小参数数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM