¿Cómo uso un método como argumento para otro método?

#include <functional>
#include <iostream>

class Foo{
  void print(std::function<void (void)> f){
    f();
    std::cout << "!";
  }
 void sayHello(){
   std::cout << "Hello";
 }
public:
  void tell(){
    print(sayHello);
  }
};

int main(){
  auto foo = Foo();
  foo.tell(); // 'Foo::sayHello': function call missing argument list; use '&Foo::sayHello' to create a pointer to member
}

Estoy recibiendo el error C3867: 'Foo::sayHello': function call missing argument list; use '&Foo::sayHello' to create a pointer to member. Si uso &Foo::sayHello then I'll get a bunch of templating errors.

¿Qué hice mal?

preguntado el 28 de mayo de 14 a las 13:05

3 Respuestas

sayHello is a non-static member function, so it has an implicit first argument, the this pointer. The simplest way to get your code to work is to use a lambda expression that captures the this puntero.

void tell(){
  print([this]{sayHello();});
}

Otra opción es std::bind

void tell(){
  print(std::bind(&Foo::sayHello, this));
}

contestado el 28 de mayo de 14 a las 13:05

You want to pass a member function as argument, however a member function must be called on an object instance.

Una posible solución es la siguiente:

void tell(){
    print(std::bind(&Foo::sayHello, this));
}

contestado el 28 de mayo de 14 a las 13:05

A member function has an additional parameter: the this pointer. You are just assuming the declaration of the function has none

void (void)

El bind () function can help you bind that pointer into it and return an object suitable for a std::function envoltura

#include <functional>
#include <iostream>

class Foo{
  void print(std::function<void (void)> f){
    f();
    std::cout << "!";
  }
  void sayHello(){
    std::cout << "Hello";
  }
public:
  void tell(){
    print(std::bind(&Foo::sayHello, this));
  }
};

int main(){
  auto foo = Foo();
  foo.tell();
}

contestado el 28 de mayo de 14 a las 13:05

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.