0

My plan is to build several listener classes which own predefined "callback hooks".

In the example below class Foo has a "callback hook" called onChange. It will be set to a default callback function during construction. It can also be set to an arbitrary function which provides the correct interface, like shown with the object f1 and the function callback().

The problem is when I want to call the object member onChange inside the for-loop the compiler says that I provide to much arguments. i am aware of the problem that i don't provide a member function to the std::mem_fn but instead an object member which is a function wrapper.

How do I manage to pass the argument to the std::function member object of class Foo without using std::bind and use std::mem_fn instead like shown in the example?

struct Foo
{
  Foo()
  {
    // default callback
    onChange = [](int value)
               -> void { std::cerr << "Foo::onChange( " << value << " )" << std::endl; };
  }

  // class destructor
  virtual ~Foo() {}

  std::function<void(int value)> onChange;

};


void callback(int value)
{
  std::cerr << "callback( " << value << " )" << std::endl;
}


int main()
{
  Foo f0;
  Foo f1;
  f1.onChange = callback;

  auto vec = std::vector<Foo>();
  vec.push_back(f0);
  vec.push_back(f1);

  auto func_wrapper = std::mem_fn( &Foo::onChange );

  for (auto f : vec)
  {
    func_wrapper(f, 42);
  }
}
Jerry YY Rain
  • 4,134
  • 7
  • 35
  • 52
iam_peter
  • 3,205
  • 1
  • 19
  • 31
  • 1
    `mem_fn` doesn't do what you think it does, when passed a pointer-to-member-variable (as opposed to pointer-to-member-function). The resulting object's `operator()` takes one parameter - a pointer or reference to `Foo` - and returns the value of the corresponding member. It does not call `operator()` on that member. – Igor Tandetnik Aug 24 '14 at 14:24
  • `auto func_wrapper = [](Foo& f, int n) {return f.onChange(n); }` Is this what you are looking for? – Igor Tandetnik Aug 24 '14 at 14:25
  • why you don't want `std::bind` ? – Piotr Skotnicki Aug 24 '14 at 14:35
  • @IgorTandetnik Thanks for your answer! Then all i have to do is use `func_wrapper(f)(42)` instead of `func_wrapper(f, 42)`. – iam_peter Aug 24 '14 at 14:55
  • @PiotrS. I just want to avoid bind, because i would have to call bind with every iteration. When i use `std::mem_fun` than i just need to call the resulting `func_wrapper` everytime. – iam_peter Aug 24 '14 at 14:57
  • you talk about using a placeholder for the Foo object? – iam_peter Aug 24 '14 at 15:03
  • "just want to avoid bind, because i would have to call bind with every iteration." There is nothing wrong in calling `std::bind` with every iteration. – n. m. could be an AI Aug 25 '14 at 04:09

0 Answers0