In my years of C++ (MFC) programming in I never felt the need to use typedef
, so I don't really know what is it used for. Where should I use it? Are there any real situations where the use of typedef
is preferred? Or is this really more a C-specific keyword?
The typedef keyword allows the programmer to create new names for types such as int or, more commonly in C++, templated types--it literally stands for "type definition". Typedefs can be used both to provide more clarity to your code and to make it easier to make changes to the underlying data types that you use.
typedef'ing structs is one of the greatest abuses of C, and has no place in well-written code. typedef is useful for de-obfuscating convoluted function pointer types and really serves no other useful purpose.
The C language contains the typedef keyword to allow users to provide alternative names for the primitive (e.g., int) and user-defined (e.g struct) data types. Remember, this keyword adds a new name for some existing data type but does not create a new type.
typedef - It s a keyword in C which lets you create custom data types, or more accurately, we can say it creates an alias name for another data type. Keep in mind that it does not create a new type, but instead adds a new name for some existing type.
typedef
is necessary for many template metaprogramming tasks -- whenever a class is treated as a "compile-time type function", a typedef
is used as a "compile-time type value" to obtain the resulting type. E.g. consider a simple metafunction for converting a pointer type to its base type:
template<typename T> struct strip_pointer_from; template<typename T> struct strip_pointer_from<T*> { // Partial specialisation for pointer types typedef T type; };
Example: the type expression strip_pointer_from<double*>::type
evaluates to double
. Note that template metaprogramming is not commonly used outside of library development.
typedef
is helpful for giving a short, sharp alias to complicated function pointer types:
typedef int (*my_callback_function_type)(int, double, std::string); void RegisterCallback(my_callback_function_type fn) { ... }
In Bjarne's book he states that you can use typedef to deal with portability problems between systems that have different integer sizes. (this is a paraphrase)
On a machine where sizeof(int)
is 4 you can
typedef int int32;
Then use int32
everywhere in your code. When you move to an implementation of C++ where sizeof(int)
is 2, then you can just change the typdef
typedef long int32;
and your program will still work on the new implementation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With