In my previous posts, typedef
and using
were introduced. If you haven't read them, I'd recommend to check them out first before proceeding with this one ( typedef
and using
).
Let's look at the following code snippets:
using flags = std::ios_base::fmtflags;
typedef std::ios_base::fmtflags flags;
Both these code snippets are equivalent! Infact, In C++11, the using
keyword when used for type alias is identical to typedef
.
using
is used specifically to type-alias template
instead of typedef
and this paper explains it very well so.
An excerpt from the paper:
It has been suggested to (re)use the keyword
typedef
— as done in the paper [4] — to introduce template aliases:
template<class T>
typedef std::vector<T, MyAllocator<T> > Vec;
That notation has the advantage of using a keyword already known to introduce a type alias. However, it also displays several disadvantages among which the confusion of using a keyword known to introduce an alias for a type-name in a context where the alias does not designate a type, but a template;
Vec
is not an alias for a type, and should not be taken for atypedef-name
. The nameVec
is a name for the familystd::vector< [bullet] , MyAllocator< [bullet] > >
– where the bullet is a placeholder for a type-name. Consequently we do not propose thetypedef
syntax. On the other hand the sentence
template<class T>
using Vec = std::vector<T, MyAllocator<T> >;
can be read/interpreted as: from now on, I’ll be using
Vec<T>
as a synonym forstd::vector<T, MyAllocator<T> >
. With that reading, the new syntax for aliasing seems reasonably logical.
You might wonder why a new keyword was not introduced and why using
was reused; there is infact a pretty good reason behind the rationale of not introducing a new keyword or new syntax every so often. The standard wants to avoid breaking old code as much as possible. This is why in proposal documents you might encounter sections like Impact on the Standard, Design decisions, and how they might affect older code. There are situations when a proposal seems like a really good idea but might not have traction because it would be too difficult to implement or too confusing, or would contradict old code which is something that should be avoided.
Thanks for giving this article a read and I'll see you in the next one 😄
Top comments (2)
The syntax is much clearer with
using
for function pointer aliases:I think so too!