模板是最好的选择吗?如果是这样,语法是否正确?

Are templates the best option? If so, is this the correct syntax?

本文关键字:语法 是否 如果 选择      更新时间:2023-10-16

这里是:

//base class
class InterfaceItem
{
public:
    //iterates through m_SubItems vector looking for an item with that name and
    //returns it
    InterfaceItem* GetSubItem(string Name);
private:
    vector<InterfaceItem*> m_SubItems;
}
//one of the classes that derive from InterfaceItem
class Window : public InterfaceItem
{
    //other functions
}

如果我输入

Window ThisWindow; //pretend it is already initialized and has sub-items
ThisWindow.GetSubItems();

它将返回一个类型为InterfaceItem*的对象,所以我不能访问任何窗口特定的函数,除非我做一些像

Window* TempWindow = static_cast<Window*>(ThisWindow.GetSubItems());

这个问题的最佳解决方案是什么?是使用函数模板吗?如果是这样,这是正确的语法吗?

class InterfaceItem
{
public:
    template<class Type*> Type* GetSubItem(string Name);
private:
    vector<InterfaceItem*> m_SubItems;
}

我试过了,我得到了一些奇怪的错误。与此无关的文件开始说明显是#include的类不存在还有一些奇怪的事情

在调用端使用static_cast实际上是一种很好的方法。您需要在某处将其称为static_cast。如果不在接收端调用,则需要在GetSubItem内部调用。

更好的方法是,如果您启用了RTTI并且可以牺牲一点性能,则使用dynamic_cast。不同之处在于,只有当subItem指向的值实际上是Window类型的实例时,dynamic_cast才会成功,否则它将返回nullptr。你可以这样写:

Window* TempWindow = dynamic_cast<Window*>(ThisWindow.GetSubItems());
if (nullptr != TempWindow) {
    // process the window
}
else { // that particular subitem is not a Window*
    // handle failure somehow
}