C++ provides implicit conversion from T *
to const T *
.
If I use T *
within a container class now, like in vector<T *>
, then there is of course no implicit conversion to vector<const T *>
anymore.
Using an reinterpret_cast
seems to work to cast the entire container, but is it actually safe to do this?
template <typename T>
const vector<const T *> & constVector(const vector<T *> & vec) {
return reinterpret_cast<const vector<const T *> &>(vec);
}
// Usage:
vector<int *> vec1;
vector<const int *> vec2 = constVector(vec1);
but is it actually safe to do this?
No, this is undefined behavior. It is only safe to use reinterpret_cast
in a very limited set of scenarios, please refer to cppreference.
If ownership is not a concern, you might want to use (or implement) a const
view over a non-const
range of objects. Googling for span
would be a good start. std::string_view
is an example of this for std::string
.
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