AudioDroid
AudioDroid

Reputation: 2322

using mem_fun with function that has more than one argument

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

Upvotes: 2

Views: 463

Answers (1)

DanDan
DanDan

Reputation: 10562

You can use boost bind:

_f2 = boost::bind(f, x, _1, _2);

Upvotes: 3

Related Questions