mardi 22 octobre 2019

Storing const* in const vector

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.

Aucun commentaire:

Enregistrer un commentaire