I know that in C++11 we can now use using
to write type alias, like typedef
s:
typedef int MyInt;
Is, from what I understand, equivalent to:
using MyInt = int;
And that new syntax emerged from the effort to have a way to express "template typedef":
template< class T > using MyType = AnotherType< T, MyAllocatorType >;
But, with the first two non-template examples, are there any other subtle differences in the standard? For example, typedef
s do aliasing in a "weak" way. That is it does not create a new type but only a new name (conversions are implicit between those names).
Is it the same with using
or does it generate a new type? Are there any differences?
All standard references below refers to N4659: March 2017 post-Kona working draft/C++17 DIS.
Typedef declarations can, whereas (until C++23) alias declarations cannot, be used as initialization statements
(+) Not including the examples of alias templates, which has already been mentioned in the original post.
(++) P2360R0 (Extend init-statement to allow alias-declaration) has been approved by CWG and as of C++23, this inconsistency between typedef declarations and alias declarations will have been removed.
Same semantics
As governed by [dcl.typedef]/2 [extract, emphasis mine]
a typedef-name introduced by an alias-declaration has the same semantics as if it were introduced by the
typedef
declaration.Subtle difference in allowed contexts
However, this does not imply that the two variations have the same restrictions with regard to the contexts in which they may be used. And indeed, albeit a corner case, a typedef declaration is an init-statement and may thus be used in contexts which allow initialization statements
whereas before C++23 (this answer may have prompted P2360R0 which addressed this niche subtlety in C++23) an alias-declaration is not an init-statement, and thus may not be used in contexts which allows initialization statements