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
?
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
?
You can use a
const_cast
if you want to, but it's not really needed -- non-const can be converted to const implicitly.You have an implicit conversion if you pass an non const argument to a function which has a const parameter
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:
STL since C++17 now provides
std::as_const
for exactly this case.See: http://en.cppreference.com/w/cpp/utility/as_const
Use:
Instead of:
const_cast
can be used to addconst
ness behavior too.From cplusplus.com:
You don't need
const_cast
to addconst
ness:Please read through this question and answer for details.