Why in this example we need both const and non-constant getters

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 the -two functions friend elementin the Ref_t class?

+3
source share
4 answers

The difference between the two functions is that the element()non-constant vector itself is not const, but if the whole vector is const, then each is element()also const.

i.e.

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

const, , . , . , - const.

[] .

, "" ""

+1

, non const

0

, .

. if vector is const == > const == > , const const const. .

Exactly the opposite for a non-constant vector. One can change a vector element using its link.

0
source

Source: https://habr.com/ru/post/1719607/


All Articles