what does type alias do in classes?


I got curious and looked at the implementation details of the std::vector. I don’t understand a lot of the code but I was confused about the "using" declarations’. I see that a lot of classes also include those using statements or typedef within their classes. What is the point of using a using declaration within your class? Does it introduce a new member variable or something? I am confused about how it works.

using iterator               = _Vector_iterator<_Scary_val>;
using const_iterator         = _Vector_const_iterator<_Scary_val>;
using reverse_iterator       = _STD reverse_iterator<iterator>;
using const_reverse_iterator = _STD reverse_iterator<const_iterator>;


using was introduced in C++11 as a more advanced and flexible replacement for typedef, particularly in template metaprogramming.

Whether typedef or using is used, standard containers define a common set of inner type aliases, so that code can be written in a more generic manner, particularly in template metaprogramming. For instance, you can write a function that accepts any standard container as input, and then use its inner aliases without having to know the type of the container itself. This allows you to easily switch between containers without having to re-write the code that is using the containers. For example 1:

template<typename Container>
void doSomething(const Container &c) {
    for(typename Container::const_iterator iter = c.cbegin(); iter != c.cend(); ++iter) {
        // use *iter as needed ...

1: obviously, there are better ways to write this nowadays, like for(const auto &elem : c) { ... }.

So, maybe one day you start out using std::vector, eg:

std::vector<int> v;

And then later on you decide to use std::list instead, eg:

std::list<int> l;

You can change the type of container used, without having to change the function itself.

Answered By – Remy Lebeau

Answer Checked By – David Marino (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.