Constant Const Preference?

let's say that I have

class A { double a; double Value() const { return a; } double& Value() { return a; } } //later: A foo; double b = foo.Value(); 

the non-constant version will now be called. Is there a good way to force use of the const version? I think it’s possible with an actor, but I don’t think it is very elegant.

+4
source share
5 answers

You can direct it to const .

 double b = static_cast<const A&>(foo).Value(); 

(I don’t think I have ever explicitly added the const variable. I am not sure if static_cast more suitable than const_cast .)

+6
source

A bit prettier than casting - assigning a const link does not require an explicit cast:

 A foo; const auto& cfoo = foo; double b = cfoo.Value(); // will use Value()const 

In practice, if you use const religiously in all arguments of your function, when possible, you will probably go foo to bar(const A& x) at some point.

+3
source

You can accomplish what you need using a proxy:

 class A { double a; class proxy { A &a; public: proxy(A &a) : a(a) {} operator double() const { return a; } proxy operator=(double d) { aa = d; return *this; } }; public: proxy Value() { return proxy(*this); } } // ... double d = foo.Value(); // will use proxy::operator double. foo.Value() = 1.0; // will use proxy::operator= 

This requires (internal) changes for your class A , but not for code that uses it. However, it will split the code for reading and writing to the item data, so you can set breakpoints individually.

+2
source

You cannot do it very elegantly, but the least detail will determine

 class A { ... const A * operator->() const { return this; } } 

and use it

 foo->Value(); 

instead

 foo.Value(); 

only for const version

+1
source

Starting with C ++ 17, we are std::as_const() , which references the const link for you. For instance:

 #include <utility> ... A foo; double b = std::as_const(foo).value(); 
0
source

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


All Articles