Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to pass a function as a parameter in C++?

Is there any way to pass a function as a parameter in C++, like the way that functions can be passed as parameters in C? I know that it's possible to pass a function as a parameter in C using function pointers, and I want to know whether the same is possible in C++.

like image 465
Anderson Green Avatar asked Dec 04 '25 17:12

Anderson Green


1 Answers

You can do it like in C. But you can also do it the C++ way (C++11, to be exact):

// This function takes a function as an argument, which has no
// arguments and returns void.
void foo(std::function<void()> func)
{
    // Call the function.
    func();
}

You can pass a normal function to foo()

void myFunc();
// ...
foo(myFunc);

but you can also pass a lambda expression. For example:

foo([](){ /* code here */ });

You can also pass a function object (an object that overloads the () operator.) In general, you can pass anything that can be called with the () operator.

If you instead use the C way, then the only thing you can pass are normal function pointers.

like image 160
Nikos C. Avatar answered Dec 06 '25 07:12

Nikos C.