user3495256 user3495256 - 1 month ago 19
C++ Question

C++ understanding typedef

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

Answer

It's clearer if you use an using declaration:

using fpLoadLibrary = HINSTANCE(*)(char*);

That is the C++11 alternative to typedefs (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.

Comments