gpt4 book ai didi

c++ - 将参数定义为未指定的模板类型

转载 作者:行者123 更新时间:2023-11-28 03:12:00 25 4
gpt4 key购买 nike

我尝试创建一个 SSCE,因为这通常也有助于及早发现问题。但是,我似乎找不到解决方案,所以我想知道是否可以定义一个参数,它是一个未指定的模板类指针。

我定义了一个接口(interface)和一个解析器类,它应该处理 xerces 的实现细节(比如代码转换和所有这些开销)。接口(interface)类将设计为从 (SAX) 解析器创建对象,但无需处理 xerces 库。

在 Java 中,我知道我可以像这样使用未指定的泛型类型参数:

class Parser
{
public Parser(IGenericInterface<?> oImpl) {};
}

基本上我想知道如何在 C++ 中完成此操作。在下面的示例中,我在声明接口(interface)变量的行中遇到编译器错误,因为它缺少类型。但当然在类声明中,类型是未知的,应该在运行时分配,如 main 所示。

#include <iostream>
#include <string>

template <class T>
class IGenericInterface
{
public:
IGenericInterface() {};
virtual ~IGenericInterface() {};

virtual T *createInstance(void) = 0;
};

template <class T>
class Implementation : public IGenericInterface<T>
{
public:
Implementation() {};
virtual ~Implementation() {};

T *createInstance(void)
{
T * t = new T;
return t;
}
};

class Parser
{
public:
Parser(IGenericInterface *oImpl) { mImpl = oImpl; };
virtual ~Parser() { delete mImpl; };

void doSomething(void) { do whatrever is needed; t = createInstance(); };

private:
IGenericInterface *mImpl;
};

int main()
{
Parser *p = new Parser(new Implementation<int>());
sleep(3);

return 0;
}

那么我要如何定义 Parser 构造函数以使其传递任意接口(interface)参数?

最佳答案

C++ 是一种静态语言,因此任何类型都必须在编译时解析。因此,您在 Java 中所做的事情无法在 C++ 中以相同的方式完成。相反,您可以使用动态多态性(使用继承)或“静态多态性”,使用带有 CRTP 的模板(在编译时解析)。

关于c++ - 将参数定义为未指定的模板类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18174993/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com