将 mem_fun 与具有多个参数的函数一起使用
我正在尝试使用 boost:function 类。在下面的示例中,对于 foo() 调用,一切正常,但如果我想对 sum() 函数执行相同的操作,gcc 编译器会抱怨这一行:
_f2 = std::bind1st(std::mem_fun(f), x);
Does 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;
}
I am trying to work with the boost:function class. In the example below, everything works fine for the foo()-call, but if I want to do the same with the sum()-function, the gcc-compiler complains about this line:
_f2 = std::bind1st(std::mem_fun(f), x);
Does mem_func only accept functions with one argument (except for the pointer to the class object that I bind)? If so what other function can I use? Or how do I have to change this line of code?
I think there is a way with boost:bind(), but I haven't figure out how to use it in this context yet.
Here is the full code:
#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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用增强绑定:
You can use boost bind: