[英]Pass a member function to create a free function boost pointer
我试图让这段代码运行。 我快到了,但我陷入了困境:
_f = std::bind1st(
std::mem_fun(f, x);
首先请理解,我不想更改任何代码,而是要更改构造函数。 为什么? 因为我想学习。 最终,我想以这种方式编写一个包装器 class Func
,它可以同时处理自由函数和成员 function 。
那么我必须把什么作为第一个参数放在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;
}
提前致谢。
看来您只是忘记了一个括号:
_f = std::bind1st(std::mem_fun(f), x);
虽然我会初始化
Func(X *x, int (X::* f) (int))
: _f(std::bind1st(std::mem_fun(f), x))
{
std::cout << _f(5); // Call x.foo(5)
};
(在这种情况下没关系,但从长远来看,这种风格更安全。)
我会稍微重构 class 以在界面中使用boost::function
,然后用户可以决定如何以最通用的方式绑定:
struct X {
int foo(int i) { return i; };
};
class Func {
boost::function<int (int)> _f;
public:
Func( boost::function<int (int)> f ){
_f = f;
std::cout << _f(5);
};
};
int foo( int x ) { return 2*x; }
int bar( int x, int multiplier ) { return x*multiplier; }
int main() {
X x;
Func func1( boost::bind( &X::foo, &x, _1 ) ); // this does the magic
Func func2( boost::bind( &foo, _1 ) ); // you can also bind free functions...
Func func3( boost::bind( &bar, _1, 5 ) ); // or with different arguments
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.