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.
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.
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.
In general, the const qualifier is used to declare a variable as constant, meaning its value cannot change once the variable has been initialized.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With