Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
June 14, 2021 07:47 am GMT

typedef VS using in type aliases declaration in C

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 a typedef-name. The name Vec is a name for the family std::vector< [bullet] , MyAllocator< [bullet] > > where the bullet is a placeholder for a type-name. Consequently we do not propose the typedef 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, Ill be using Vec<T> as a synonym for std::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


Original Link: https://dev.to/guptaaastha/typedef-vs-using-in-type-aliases-declaration-in-c-fm2

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To