Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to pass function as an argument to another function in c++?

I need to pass function with no arguments to another function, how can I do it?

I googled a bit, and found out that I need to use std::function from functional, but didn’t understand how to pass function without arguments.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Using std::function you can achieve that like in the following example: c++ shell

#include <iostream>
#include <functional>

void myFunction() {
  std::cout << "Hello world!\n";
}

void foo(std::function<void()> f) {
  f();
}

int main() {
  foo(myFunction); // Pass the function without arguments
  return 0;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading