Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

casting non const to const in c++

I know that you can use const_cast to cast a const to a non-const.

But what should you use if you want to cast non-const to const?

like image 261
kamikaze_pilot Avatar asked May 02 '11 05:05

kamikaze_pilot


People also ask

Can you pass a non-const to a const?

Converting between const and non-const For instance, you can pass non-const variables to a function that takes a const argument. The const-ness of the argument just means the function promises not to change it, whether or not you require that promise.

Can you cast a const?

const_cast can be used to add const ness behavior too. From cplusplus.com: This type of casting manipulates the constness of an object, either to be set or to be removed.

Can const methods be used by non-const objects?

const member functions may be invoked for const and non-const objects. non-const member functions can only be invoked for non-const objects. If a non-const member function is invoked on a const object, it is a compiler error.

How do you get rid of const?

Changing a constant type will lead to an Undefined Behavior. However, if you have an originally non-const object which is pointed to by a pointer-to-const or referenced by a reference-to-const then you can use const_cast to get rid of that const-ness.


2 Answers

const_cast can be used in order remove or add constness to an object. This can be useful when you want to call a specific overload.

Contrived example:

class foo {     int i; public:     foo(int i) : i(i) { }      int bar() const {         return i;         }      int bar() { // not const         i++;         return const_cast<const foo*>(this)->bar();      } }; 
like image 171
Motti Avatar answered Oct 12 '22 07:10

Motti


STL since C++17 now provides std::as_const for exactly this case.

See: http://en.cppreference.com/w/cpp/utility/as_const

Use:

CallFunc( as_const(variable) ); 

Instead of:

CallFunc( const_cast<const decltype(variable)>(variable) ); 
like image 41
Scott Langham Avatar answered Oct 12 '22 08:10

Scott Langham