When I read the shared_ptr, I found a piece of code:
void(*)()
How to interpret it?
When I read the shared_ptr, I found a piece of code:
void(*)()
How to interpret it?
It is a pointer to a function type, which can be used for all the functions which have no arguments and returns void.
For example:
void function_1() {}
void function_2() {}
void(*func_1_ptr)() = function_1; // or = &function_1;
void(*func_2_ptr)() = function_2; // or = &function_2;
Now func_1_ptr holds the pointer to the function function_1, and func_2_ptr holds the pointer to function_2.
You can make the type more intuitive by using declaration.
using FunPtrType = void(*)();
and now you could write
FunPtrType func_1_ptr = function_1; // or = &function_1;
//Type identifier function
FunPtrType func_2_ptr = function_2; // or = &function_2;
This is the type of a pointer to a function, which takes no arguments and returns void.
The asterisk in between an open-close parenthesis (*) represents the declaration of a function-pointer. The left and right of this represent the return type and function arguments of the function that it will point to.
So basically in your case:
void printHello()
{
std::cout<<"Hello";
}
void(*fPtr)() = printHello;
In C++ you can do the same using a better OOP way:
std::function<void()> fPtr = printHello;
fPtr();
You will have to include the functional header