简体   繁体   中英

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

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.

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
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*);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM