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
?
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) );
You don't need const_cast
to add const
ness:
class C;
C c;
C const& const_c = c;
Please read through this question and answer for details.
You can use a const_cast
if you want to, but it's not really needed -- non-const can be converted to const implicitly.
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.
You have an implicit conversion if you pass an non const argument to a function which has a const parameter