模板是最好的选择吗?如果是这样,语法是否正确?
Are templates the best option? If so, is this the correct syntax?
这里是:
//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
}
相关文章:
- 特征库是否修改C++语法
- std::is_invocable 用于测试任意方法是否存在的语法(不仅是运算符())
- 标准库中的任何正则表达式语法是否支持 (?(定义)用于子模式参考?
- 放置/分段语法是否可能出现懒惰"operator or"重载?
- 统一取消引用语法是否可行?
- 结构化绑定语法是否可以在多态 lambda 中使用
- 罗斯林是否支持C++生成语法树
- 是否有任何语法可以缩短此代码
- 将任何类型的表达式放在 c++ 的初始化列表中在语法上是否正确?
- 像这样的PIMPL实现是否有任何简单的语法
- 是否有用于C++的类似 C 的语法脚本语言解释器?
- 是否可以在尾随返回类型语法中直接使用参数值(不是其类型,而是值本身)
- 是否有任何法律语法允许引号出现在 javascript 中的标识符字符旁边?(如"so")
- 是否有任何 DirectX 11 (HLSL 5.0) 等效于 DirectX 9 纹理"string function"语法?
- 是否可以避免使用lambda中的尾随返回型语法
- 是否可以通过从lambda的引用中返回T型对象,而无需使用尾随返回类型语法
- 是否可以通过与EasyLogging 相同的方式来创建一个C 类,以模仿STD :: COUT语法
- 此模板语法是否非法
- 此语法是否非法
- 模板是最好的选择吗?如果是这样,语法是否正确?