【问题标题】:Passing void method with parameters to another method with std::function and std::bind C++使用 std::function 和 std::bind C++ 将带参数的 void 方法传递给另一个方法
【发布时间】:2017-12-10 04:21:08
【问题描述】:
class A
{
public:
    A() {}

    void print(std::function<void(int)> func);

    virtual ~A() {}
};

void A::print(std::function<void(int)> func)
{
    func();
}

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

int main()
{
    A a;

    a.print(std::bind(&printInt, 3));

    return 0;
}

假设我有这个代码示例。如何将 void 方法 printInt(int a) 传递给 A::print(std::function func) 并在那里调用已传递的函数?我得到“候选人期望 1 个参数,提供 0 个参数”,但我不知道如何处理。

编辑: 我应该提到它,但我的目标是传递该整数,但实际上我不知道如何传递。当我尝试这样的事情时:

void A::print(std::function<void(int a)> func)
{
 func(a);
}

我得到“错误:‘a’没有在这个范围内声明”。

【问题讨论】:

  • 您正在调用一个函数,该函数采用不带参数的int (func())。

标签: c++ c++11


【解决方案1】:

如果您不打算将任何参数传递给func,则应为std::function&lt;void(void)&gt;void(int) 的签名意味着你打算给它一个整数,它会期望。而且您的代码显然没有提供所需的参数。


如果您确实打算将参数传递给func,则它需要是A::print 的参数,如下所示:

void A::print(std::function<void(int)> func, int a) {
  func(a);
}

您尝试将函数参数命名为a,这是没有实际意义的。由于A::print 中没有a 可供参考。以上也意味着你可以省去bind

a.print(&printInt, 3);

【讨论】:

  • 那你就不用std::bind()了,你会用std::ptr_fun代替。
  • @StoryTeller 我的坏先生
  • @SornelHaetir - 不,你不会使用std::ptr_fun,请不要推荐它。它在 C++11 中已被弃用,并在 C++17 中永远消失。
  • 使用 C++11,我会避免使用 std::bind 并改用 lambda。对我来说,lambda 表达式更容易阅读。 2¢
  • @Eljay - 我同意。但特别是在 C++11 中,如果您需要将某些东西移入闭包中,std::bind 是不可避免的。在 C++14 中,一直是 lambda。
【解决方案2】:

您的 bind() 创建了一个不带参数的函数,但 A::print 需要一个带 1 的函数。然后它尝试调用该函数,就好像它不带参数一样。

答案是将 A::print 更改为采用不带参数的 std::function。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-20
    • 2016-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-20
    相关资源
    最近更新 更多