Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there cases where a typedef is absolutely necessary?

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; 
like image 363
fredoverflow Avatar asked Aug 09 '11 15:08

fredoverflow


People also ask

When should you use typedef?

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.

Is it good to use typedef?

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.

What is typedef use?

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.

What is the scope of a typedef?

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.


1 Answers

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.

like image 64
fredoverflow Avatar answered Oct 14 '22 20:10

fredoverflow