#Utilising std map

17 messages · Page 1 of 1 (latest)

glad forge
#

in the following code I have a small class which: Adds, Removes, Finds, and Returns all values of a T object. However I'm having troubles with the Find and getValues functions as all my attempts to return a reference or pointer has resulted in Error cannot convert _Ty2 to T*.

Here is the code:

template <typename T>
class ObjectManager {
public:
    // Constructor
    ObjectManager() {}

    // Destructor
    virtual ~ObjectManager() {}

    // Add an object to the manager
    void AddObject(const std::string& name, T object) {
        objects_[ToLower(name)] = object;
    }

    // Remove an object from the manager
    void RemoveObject(const std::string& name) {
        objects_.erase(ToLower(name));
    }

    T* FindObject(std::string name) {
        auto itr = objects_.find(name);
        return itr != objects_.end() ? itr->second: nullptr;
    }


    // Get a vector of all the values in the map
    std::vector<T*> GetValues() {
        std::vector<T*> values;
        values.reserve(objects_.size());

        for (auto& object : objects_) {
            values.emplace_back(object.second);
        }
        return values;
    }

private:
    // Map of objects in the manager, with string names as keys
    std::map<std::string, T> objects_;
}:

and here is how i intend to use the functions:

// m_buttons = ObjectManager<ObjectManager<Button>>
for (Button* button : m_buttons.FindObject("both")->GetValues()) {
  button->setClicked(false);
}
upper sorrelBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question run !howto ask.

native dove
#

itr->second is a T which is not convertible to a T * most of the time.

#

Same with object.second.

#

"Error cannot convert T to T * with T = <actual type> in <file>:<line>" is what the compiler should have said.

glad forge
#

what can i use to convert T to T* then? could i just turn it into a pointer like any other variable

native dove
#

Yes

#

Just add an & before it.

glad forge
#

when i run the code
getButton("both", "Neural Net")->flipClicked();
i get the error:

#

i checked to make sure that im trying to read a valid map value

native dove
#

It's saying that the object you called flipClicked on was invalid (nullptr).

glad forge
#

is there a unique way that maps update? while debugging it shows that the map is empty, even after adding values to it

native dove
#

No, immediately after you add a value it's added and there.

#

And unlike for std::vector, its iterators are stable.

#

(meaning that you can point to an object inside the map and add and remove objects (except the one you're pointing at) and the pointer stays valid)

glad forge
#

oh i just forgot to lower the string before seaching

glad forge
#

!solved