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;
Answering the "Are there cases where a typedef is absolutely necessary?" from the question title, here is one example of where a typedef is needed:
See the results here: http://ideone.com/JPUra
One case (unrelated to your question) where a
typedef
is required is when using theva_arg()
macro. Quoting the C99 standard (7.15.1.1):...
Ah, I just remembered the
identity
meta-function. It is possible to writewith the following definition of
identity
:You could argue that
identity
still uses atypedef
, but this solution is "good" enough for me.A
typedef
is not a macro your second example is not equivalent to the first. In the first case yourtypedef
is defining a functor then using that type in a cast operator of the functor type. In the second the operator is using bad syntax as there is no operator specified because there is no type. I'm not sure how to write it but there is a way usually.Typedefs aren't really necessary except for making human readable code in TMP and even then it depends on what kind of human you are.Since I can't come up with the alternative syntax maybe typedefs are necessary in some cases. I just thought of another one possibly. Say you had a template with specializations which contained a static method with a return type like below:
I think in this case also you would need the typedef in order to call the static method regardless of specialization as otherwise the method could confuse the compiler because the return types would differ but it wouldn't be a proper overload.
I just ran across this issue, with clang++:
and there's a C++11 STL template which covers the identity<T> functionality:
My analysis says that it is not possible without using
typedef
. The compiler sees(
as the first token and assumes you are overloading() operator
, which shouldn't have any arguments (The arguments would come in next set of parenthesis). Putting any set of extra parenthesis wouldn't help either - but would actually confuse the compiler and hence set of more errors.Most of the STL code is on top of
typedef
initions, and we should/must use them!