【问题标题】:using mem_fun with function that has more than one argument将 mem_fun 与具有多个参数的函数一起使用
【发布时间】:2011-07-08 15:09:10
【问题描述】:

我正在尝试使用 boost:function 类。在下面的示例中,对于 foo() 调用来说一切正常,但是如果我想对 sum() 函数做同样的事情,gcc 编译器会抱怨这一行:

_f2 = std::bind1st(std::mem_fun(f), x);

mem_func 是否只接受带有一个参数的函数(指向我绑定的类对象的指针除外)?如果是这样,我可以使用什么其他功能?或者我要如何更改这行代码?

我认为 boost:bind() 有一种方法,但我还没有弄清楚如何在这种情况下使用它。

这里是完整的代码:

#include <boost/function.hpp>
#include <iostream>

class X
{
public:

    int foo(int i){return i;};
    int sum(int i, int j) {return i+j;};
};

class Func
{

public:

   Func(X *x,  int (X::* f) (int))
   {
      _f1 = std::bind1st(std::mem_fun(f), x);
      std::cout << _f1(5); // Call x.foo(5)
   };

   Func(X *x,  int (X::* f) (int, int))
   {
      _f2 = std::bind1st(std::mem_fun(f), x);
      std::cout << _f2(5, 4); // Call x.foo(5,4)
   };

private:

    boost::function<int (int)> _f1;
    boost::function<int (int, int)> _f2;
};


int main()
{

    X x;

    Func func1(&x, &X::foo);
    Func func2(&x, &X::sum);

    return 0;
}

【问题讨论】:

    标签: c++ function boost function-pointers


    【解决方案1】:

    你可以使用 boost 绑定:

    _f2 = boost::bind(f, x, _1, _2);
    

    【讨论】:

    • 谢谢,这很有帮助,我必须阅读更多关于绑定类的内容,如果您了解语法,那么它非常好用且易于使用。
    • 它比使用 bind1st/bind2nd 好得多,我不记得使用哪一个了。您可以将 _f1 替换为 _f1 = boost::bind(f, x, _1);
    猜你喜欢
    • 2018-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-19
    • 1970-01-01
    • 2021-12-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多