Reputation: 153
I have done some research but I just cannot get my head around what a typedef
is.
I have found this example:
typedef HINSTANCE(*fpLoadLibrary)(char*)
Can someone explain what the typedef
is doing here and furthermore what does it mean to have the values in parentheses
Upvotes: 4
Views: 1115
Reputation: 1
It's a typedef
for a function pointer to a function with the signature
HINSTANCE fn (char*);
and used with the name fpLoadLibrary
.
You can use it like
fpLoadLibrary fptr = fn; // << from above
Upvotes: 0
Reputation: 50568
It's clearer if you use an using declaration:
using fpLoadLibrary = HINSTANCE(*)(char*);
That is the C++11 alternative to typedef
s (in fact, the standard says that - A typedef-name can also be introduced by an alias-declaration).
As you can see now, fpLoadLibrary
is an alias for the type pointer to the function type HINSTANCE(char*)
.
The types in parentheses are nothing more than the expected types of the parameters of the function type.
The typedef
in your snippet means exactly the same, even if (my opinion) is harder to read.
Now suppose you a have a function like this:
HINSTANCE f(char*) {}
You can use the type above introduced as it follows:
fpLoadLibrary fp = &f;
Then you can invoke f
also through fp
as:
fp(my_char_ptr);
As an example, it could be helpful when you want to store aside a function pointer and you pick the right function up from a set of available functions all having the same signature.
Upvotes: 4
Reputation: 206737
typedef HINSTANCE(*fpLoadLibrary)(char*)
declares fpLoadLibrary
to be type that is a pointer to a function that takes a char*
as input and returns a HINSTANCE
.
Analogy with a simpler typedef
.
For an int
,
int ip; // Declares a variable.
typedef int aType; // Declares type. aType is an alias for int
For a function pointer,
// Declares a variable.
// ftpr is a pointer to a function that takes char*
// as argument and returns a HINSTANCE.
HINSTANCE (*fptr)(char*);
// Declares a type.
// fpLoadLibrary is an alias for the type "pointer to function that takes
// a char* as argument and returns a HINSTANCE.
typedef HINSTANCE (*fpLoadLibrary)(char*);
Upvotes: 0