How would I make a function that takes address of another function as a parameter so that passing it is not necessary.
My first solution was this:
void empty_func() {}
void func(void (*additional_func) () = &empty_func)
{
additional_func();
// some other code...
}
This solution works.
However, I was wondering is there some more convenient way to make passing additional_function
optional, so I do not have to make a new function (empty_func()
) and passing it as a default argument?
As function pointers are also a pointer and null-equivalent for pointer types are nullptr
so you can assign the value to this default parameter as nullptr
.
Also, don't miss forget to add nullptr
check before using it.
void func(void (*additional_func) () = nullptr )
{
if(additional_func)
{
additional_func();
}
//some other code...
}
Also, it is more convenient to define an alias for this function-pointer as use like following:
using TPFunc = void (*) ();
void func( TPFunc additional_func = nullptr )
{
if(additional_func)
{
additional_func();
}
//some other code...
}
But it is best to use features from functional
header file instead of these raw-function-pointers. Following is an example to achieve this using functional
header file:
#include <iostream>
#include <functional>
using TPFunc = std::function<void()>;
void func( TPFunc additional_func = nullptr )
{
if(additional_func)
{
additional_func();
}
else
{
std::cout<< "Function pointer is `nullptr`\n";
}
//some other code...
}
void fun1()
{
std::cout << "In 'void fun1()'\n";
}
void fun2()
{
std::cout << "In 'void fun2()'\n";
}
int main()
{
func();
func(fun1);
func(fun2);
std::cout<< "Done";
return 0;
}
Output:
Function pointer is `nullptr`
In 'void fun1()'
In 'void fun2()'
Done