why do we need both const and non-const getters in this example

c++

Solution

The difference between the two functions is that an `element()` of a non-const vector is itself non-const, but if the entire vector is const, then each `element()` is also const.

i.e.

int main() {
   std::vector<A> const cva = foo();
   ARef_t ar;
   A const& a = element(ar, cva);
}

Problem

I came across this example here: ``` #include <vector> #include <cstddef> template<typename Tag> class Ref_t { std::size_t value; friend Tag& element(Ref_t r, std::vector<Tag>& v) { return v[r.value]; } friend const Tag& element(Ref_t r, const std::vector<Tag>& v) { return v[r.value]; } public: // C'tors, arithmetic operators, assignment }; struct A{}; struct B{}; typedef Ref_t<A> ARef_t; typedef Ref_t<B> BRef_t; int main() { std::vector<A> va; ARef_t ar; A& a = element(ar, va); } ``` So the question is why do we need -two `friend element` functions in Ref_t class?

Original source

Related problems