Consider the following excerpt from the safe bool idiom:
typedef void (Testable::*bool_type)() const; operator bool_type() const;
Is it possible to declare the conversion function without the typedef? The following does not compile:
operator (void (Testable::*)() const)() const;
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.
It can almost be necessary when dealing with templates that require multiple and/or variable parameters. The typedef helps keep the naming straight. Not so in the C programming language. The use of typedef most often serves no purpose but to obfuscate the data structure usage.
typedef is a reserved keyword in the programming languages C and C++. It is used to create an additional name (alias) for another data type, but does not create a new type, except in the obscure case of a qualified typedef of an array type where the typedef qualifiers are transferred to the array element type.
A typedef is scoped exactly as the object declaration would have been, so it can be file scoped or local to a block or (in C++) to a namespace or class.
Ah, I just remembered the identity
meta-function. It is possible to write
operator typename identity<void (Testable::*)() const>::type() const;
with the following definition of identity
:
template <typename T> struct identity { typedef T type; };
You could argue that identity
still uses a typedef
, but this solution is "good" enough for me.
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