我正在尝试使用 boost:function 类。在下面的示例中,对于 foo() 调用,一切正常,但如果我想对 sum() 函数执行相同操作,gcc 编译器会提示这一行:
_f2 = std::bind1st(std::mem_fun(f), x);
mem_func 是否只接受带有一个参数的函数(除了指向我绑定(bind)的类对象的指针)?如果可以的话我还可以使用什么其他功能?或者我该如何更改这行代码?
我认为有一种使用 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;
}
最佳答案
您可以使用 boost 绑定(bind):
_f2 = boost::bind(f, x, _1, _2);
关于c++ - 将 mem_fun 与具有多个参数的函数一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6626467/