I'm trying to learn what I think should be smart pointers, but I need some direction as I'm not sure I'm doing it correctly.
Suppose I have a vector of IGUIElements, and I want to set the text of the element depending on it's subclass type.
Here's how I have been doing it:
Code: Select all
class Element {
public:
std::string type;
IGUIElement* elem;
Element::Element(IGUIElement* elem, std::string type) { this->elem = elem; this->type = type; }
};
std::vector<Element*> elements;
int main()
{
elements.push_back(new Element((IGUIElement*)guienv->addStaticText(L"Test Text", rect<s32>(0,0,10,10)), "IGUIStaticText"));
elements.push_back(new Element((IGUIElement*)guienv->addButton(rect<s32>(0,0,10,10),0,-1,L"Test button"), "IGUIButton"));
for (Element* elem : elements)
{
if (elem->type == "IGUIStaticText")
((IGUIStaticText*)elem->elem)->setText(L"New Text!");
else if (elem->type == "IGUIButton")
((IGUIButton*)elem->elem)->setText(L"New Text!");
}
return 0;
}
Code: Select all
// …
int main()
{
// …
for (Element* elem : elements)
{
elem->elem->setText(L"New Text!");
}
}
I need to be able to cast the object back to it's derived class, without casting for each element type like (IGUIButton*), while the vector stores it as the base class.
I believe I should be doing something with smart pointers, such as
Code: Select all
std::vector<std::unique_ptr<IGUIElement*>> elements
Help would be appreciated. Thanks,