简体   繁体   中英

How do I use a method as an argument for another method?

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

I am getting the error C3867: 'Foo::sayHello': function call missing argument list; use '&Foo::sayHello' to create a pointer to member C3867: 'Foo::sayHello': function call missing argument list; use '&Foo::sayHello' to create a pointer to member . If I use &Foo::sayHello then I'll get a bunch of templating errors.

What did I do wrong?

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 pointer.

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

Another option is std::bind

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

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

A possible solution is the following:

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

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

void (void)

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

#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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM