Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the const qualifier in this type alias dropped? [duplicate]

TL;DR

Given the following type:

struct A
{
    std::vector<std::string> vec;

    using reference = std::iterator_traits<decltype(vec)::iterator>::reference;
    using const_reference = const reference;
};

Why is reference == const_reference? Why is the const qualifier dropped in the second type alias?

See the example on godbold which shouldn't compile.

Details

I have a templated class that takes a bunch of iterators (-types) as template arguments. From these iterators I need to deduce the reference and const reference type because I have some member functions like:

struct A
{
    std::vector<std::string> vec;

    using reference = std::iterator_traits<decltype(vec)::iterator>::reference;
    using const_reference = const reference;

    const_reference foo() const
    {
        return vec[0];
    }
};

By dropping the const qualifier, I'm effectively returning a reference in foo which is illegal because it's a const member function and so the compiler throws.

like image 965
Timo Avatar asked May 22 '18 14:05

Timo


People also ask

What is const type qualifier?

The const qualifier explicitly declares a data object as something that cannot be changed. Its value is set at initialization. You cannot use const data objects in expressions requiring a modifiable lvalue. For example, a const data object cannot appear on the lefthand side of an assignment statement.

What is const qualifier in C?

In general, the const qualifier is used to declare a variable as constant, meaning its value cannot change once the variable has been initialized.


1 Answers

It is dropped. What we call a "const reference" is really a reference to const - const int&.

Having an int& and adding const would make that int& const. But such a const is dropped.

Your problem is similar to the difference between const int* and int* const. Except that for references, int& and int& const is the same type - the const is ignored.

like image 141
Bo Persson Avatar answered Oct 28 '22 19:10

Bo Persson