Quantcast
Channel: When should I use typedef in C++? - Stack Overflow
Viewing all articles
Browse latest Browse all 14

Answer by j_random_hacker for When should I use typedef in C++?

$
0
0

Template Metaprogramming

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.

Simplifying Function Pointer Types

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) {    ...}

Viewing all articles
Browse latest Browse all 14

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>