本文介绍了std :: function和std :: bind行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个代码:

#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);
}

您可以解释一下 std的可能性: :绑定时返回 std :: function< void(int)> $ c> function?

Can you please explain how it's possible for std::bind to return std::function<void(int)> when binding void() function?

如何使用 void(int)调用 void() / code> functor?

How it's possible to call void() function by using void(int) functor?

推荐答案

作为 code>只决定多少占位符( _1 )将被绑定,以及作为什么类型。

The signature passed as the template argument for function only determines how many place holders (_1) will be bound, and as what types.

实际函数的调用只使用绑定函数实际需要的参数数量。实际上,多余的参数被忽略。

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);
}

列印

gun(43)

这篇关于std :: function和std :: bind行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-16 13:22
查看更多