Is there an efficient and safe way to cast a std::vector<const Point*>&
to std::vector<Point*>&
?
Doing reinterpret_cast<std::vector<Point*>&>(constvec)
would probably work correctly but is probably undefined behavior.
The only standard option seems to be constructing a new std::vector<Point*>
and adding each const_cast
ed element manually, but then the program would needlessly allocate memory for it.
Edit: The program looks like this (simplified):
class A {
private:
int some_data[10];
public:
template<typename Callback>
void algo(Callback callback) const {
std::vector<const int*> values { &some_data[0], &some_data[5], &some_data[3] };
// Class is const-correct internally, so only have const access to data here.
// Making it mutable is not easily possible in the real code,
// as there are constructs similar to iterator/const_iterator in the class hierarchy.
callback(values);
}
template<typename Callback>
void algo(Callback callback) {
// Hack to avoid copying the entire algorithm implementation
auto cb = [&](const std::vector<const int*>& vec) {
callback(....); // <--- should be const std::vector<int*>
}
static_cast<const A*>(this)->algo(cb);
}
};
Another option would be to implement the algorithm in the non-const variant, and then const_cast<A&>(*this).algo()
for the const variant. But this seems more dangerous since the A
object might have been created as const (const A a;
) and then it is UB.