Search code examples
c++c++11autoconst-iterator

How does one achieve const_auto, since C++11 lacks it?


The auto type of C++11 is handy, so now one wants a const_auto type, too. For example, supposing std::list<T> a;, if

auto p = a.begin();

has the type std::list<T>::iterator, then one wishes that

const_auto p = a.begin();

had the type std::list<T>::const_iterator. Unfortunately, C++11 does not seem to have heard of const_auto. Therefore, how can one achieve the desired effect with good style, please?

(For information, a related question is asked and answered here.)


Solution

  • C++11 does allow you to write

    const auto p = a.begin();
    

    However, this doesn't do what you want. This makes a regular iterator to non-constant data whose value cannot be changed.

    The type of the right-hand side a.begin()is determined by the type of a, and not by anything on the left-hand side. If a is non-const, then the non-const version of a.begin() will be called. So, you could cast a to a const& and then use it, or you could make a constant reference to a and use that:

    const auto& b = a;
    auto p = b.begin();
    

    However, a simpler approach would be to use the newly introduced .cbegin() and .cend():

    auto p = a.cbegin();