The relevant interface code that I have to deal with consists of two functions, one that retrieves objects, and the other one where I have to submit the objects as vectors. The problem is, that the retrieval function returns const Object*, but the submit function expects const vector<Object*>.
I know this is solveable with const_cast<Object*>, but is there a different, cleaner way?
Here is code that demonstrates the problem:
#include <vector>
//////////// REPRESENTATIVE INTERFACE IMPLEMENTATION, DO NOT TOUCH ///////
struct Object{};
class Interface{
public:
size_t getNumObjects() const {return 10;}
const Object* getObject(size_t index) const {return nullptr;}
};
const Interface interface;
void submitObjects(const std::vector<Object*> &objects);
//////////////////////////////////////////////////////////////////////
// Task: take all objects from 'interface' and submit them to 'submitObjects'.
int main(){
std::vector<const Object*> objects;
for(size_t i = 0; i < interface.getNumObjects(); i++){
const Object* object = interface.getObject(i);
objects.push_back(object);
}
submitObjects(objects); // ERROR: no known conversion from 'vector<const Object *>' to 'const vector<Object *>'
return 0;
}
The only way that I could come up with to solve that problem is to make objects a std::vector<Object*> and insert the objects with objects.push_back(const_cast<Object*>(object));, but I feel like there has to be a better solution.
Any ideas are appreciated.
Some more background info why this is a valid problem:
const vector<Object*> can only deliver const Object*, as seen in all of its getter overloads, like seen here: https://de.cppreference.com/w/cpp/container/vector/operator_at
Therefore, vector<const Object*> is almost never used in interfaces. Therefore, the idea of combining a lot of const Object* in one big const vector<Object*> is a valid concept, but seems impossible to construct without const_cast.
EDIT: Statement above is incorrect, thanks for clarifying.
const std::vector<Object*> can produce non-const pointers, because my understanding of pointer constness was incorrect.