开发者

Pass a member function to create a free function boost pointer

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 t开发者_如何学JAVAutorial 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.


It seems you just forgot a paren:

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

Although I would initialize with

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

(It doesn't matter in this case, but this style is safer in the long run.)


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:

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
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜