传递一个成员函数来创建一个自由函数boost指针
我尝试让这段代码运行。我快到了,但我被困住了:
_f = std::bind1st(
std::mem_fun(f, x);
首先,请理解我不想更改任何代码,但想更改构造函数。为什么?因为我想学习。最终我想编写一个包装类 Func
,它可以以这种方式同时处理自由函数和成员函数。
那么我必须将什么作为 std::mem_func() 调用中的第一个参数??? 我尝试了很多事情。
可能这是重复的,但我不知道如何搜索这个问题。我缺乏词汇量。如果有人可以指出教程或其他东西,这将帮助我表达这个问题,我也将不胜感激。
这是完整的示例代码:
#include <boost/function.hpp>
#include <iostream>
struct X
{
int foo(int i)
{
return i;
};
};
class Func
{
public:
Func(X *x, int (X::* f) (int))
{
_f = std::bind1st(
std::mem_fun(f, x);
std::cout << _f(5); // Call x.foo(5)
};
private:
boost::function<int (int)> _f;
};
int main()
{
X x;
Func func(&x, &X::foo);
return 0;
}
提前致谢。
I try to get this code running. I am almost there but I got stuck with the line:
_f = std::bind1st(
std::mem_fun(f, x);
First of all please understand that I don't want to change any code, but the constructor. Why? Because I want to learn. Eventually I want to write a wrapper class Func
, that can handle free functions and member function at the same time, in this very manner.
So what wuld I have to put as the first argument inside the std::mem_func()
-call???
I tried numerous things.
Probably this is a duplicate, but I don't know how to search for this problem. I lack the vocabulary. If someone can point to a tutorial or something, that would help me to express this problem, I would also appreciate it.
Here is the full sample code:
#include <boost/function.hpp>
#include <iostream>
struct X
{
int foo(int i)
{
return i;
};
};
class Func
{
public:
Func(X *x, int (X::* f) (int))
{
_f = std::bind1st(
std::mem_fun(f, x);
std::cout << _f(5); // Call x.foo(5)
};
private:
boost::function<int (int)> _f;
};
int main()
{
X x;
Func func(&x, &X::foo);
return 0;
}
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
看来你只是忘记了一个括号:
虽然我会初始化
(在这种情况下并不重要,但从长远来看这种风格更安全。)
It seems you just forgot a paren:
Although I would initialize with
(It doesn't matter in this case, but this style is safer in the long run.)
我会稍微重构该类以在界面中使用
boost::function
,然后用户可以决定如何以最通用的方式进行绑定:I would refactor the class slightly to use
boost::function
in the interface, and then the user can decide how to bind in the most generic way: