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
?
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.
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.
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.
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.
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(); } };
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) );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With