DEV Community

loading...

typedef VS using in type aliases declaration in C++

Aastha Gupta
i design things and write code
・2 min read

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;
Enter fullscreen mode Exit fullscreen mode
typedef std::ios_base::fmtflags flags;
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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> >;

Enter fullscreen mode Exit fullscreen mode

can be read/interpreted as: from now on, I’ll 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 😄

Discussion (2)

Collapse
pgradot profile image
Pierre Gradot

The syntax is much clearer with using for function pointer aliases:

using Pointer = void(*)(int, double);
typedef void(Pointer*)(int, double);
Enter fullscreen mode Exit fullscreen mode
Collapse
guptaaastha profile image
Aastha Gupta Author

I think so too!