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++.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With