#include <iostream>
#include <functional>
void task()
{
std::cout << "Task" << std::endl;
}
void task2()
{
std::cout << "Task2" << std::endl;
}
void doTask(std::function<void()> func)
{
for ( int a = 0; a < 10; a++ )
{
func();
}
}
int main()
{
if (true)
{
dotask(task);
}
else
{
dotask(task2);
}
return 0;
}
Now you might ask why use std::function when using a C function pointer works also? Well there is quite a few benefits actually. First of all std::function works with more then just function pointers, it works with any callable object which include
#include <iostream>
#include <functional>
struct testFunctor
{
voidoperator()() const { std::cout << "Testing..." << std::endl; }
};
void doTask(std::function<void()> func)
{
for ( int a = 0; a < 10; a++ )
{
func();
}
}
int main()
{
doTask(testFunctor());
return 0;
}
If you tried using a functor with a C function pointer you would be out of luck as far as I know.
Another benefit of using std::function would be that it is much cleaner looking code and you can determine more quickly what type of function it is looking for. For example std::function<void (int, int)> someFunc; compared to void (func*)(int, int). For me it is much easier to tell that it wants a function that returns void and has two integer parameters in the std::function object then it is with a C function pointer.
And lastly when using std::function it is much easier to work with storing and using members functions. There is a few more features that std::function and it's helpers provide but they need a bit more in-depth discussion to explain so will leave that for you to research.