Using pointers, I can create all combinations of (const/non_const) to (T / const T) for any type T, as discussed in detail this answer.
But using references, how can I define a reference to a variable which can be dereferences (like an iterator), such that the dereferenced reference gives a const access?
For example, consider this program:
#include <array>
int main()
{
std::array<int, 3> a{0, 0, 0};
auto const& iter = a.begin();
// iter++; // Error!
(*iter)++;
}
iter
is const
variable, and if you uncomment the line iter++
the code cannot compile.
But iter
dereferences to a non-const int, which in fact can be incremented with (*iter)++
. In a sense, iter
mimics int * const
, i.e., a const pointer to int.
Is it possible to instead have a (const or non_const) reference iter
, such that *iter
is a const int?
Please bear in mind that I am aware that I could use const auto& iter = a.cbegin()
in the example above. The purpose of the question is how to define iter
, such that, when dereferenced, give a const access, irrespective of what is on the right of the equal operator.
For iterators I can imagine to explicitly bind to a const_iterator
, like:
const decltype(a)::const_iterator& iter = a.begin();
This solution works because I know that the equivalent "const-access" of an iterator
is a const_iterator
.
But, more generally:
(some type)& iter = rhs
If all I know is that *rhs
is a int, is it possible to find out the type of iter, such that *iter
is a const int?
Another point worth to consider is the possible cost of the conversion of rhs
.