【发布时间】:2020-07-04 09:53:28
【问题描述】:
在我的项目中,我有一个带有接口的基本抽象类,派生类实现了该接口。这些派生类具有接受不同类型参数的通用函数。我使用函数模板在派生类中编写了这些通用函数。
我想将这些模板化函数添加到我的基类中的接口中。所以我可以实现多态性:在其他函数中接受基类,在派生类中调用这些模板函数。
当我们有普通函数时,我们会做 virtual 和 override,但你不能用模板函数做 virtual。
我尝试在我的抽象基类中执行纯抽象模板化函数,但它不起作用。
这是一个小程序,它具有我正在尝试实现的功能,但由于virtual <template... 而无法编译:
#include <vector>
class ObjectTransformerBaseAbstractClass {
public:
virtual template<typename TStructure> TStructure ToStructure(std::vector<unsigned char> bytes) = 0;
virtual template<typename TStructure> std::vector<unsigned char> ToBytes(TStructure structure) = 0;
};
class ObjectTransformer1 : public ObjectTransformerBaseAbstractClass {
template <typename TStructure> TStructure ToStructure(std::vector<unsigned char> bytes) {
// some implementation
}
template <typename TStructure> std::vector<unsigned char> ToBytes(TStructure structure) {
// some implementation
}
};
class ObjectTransformer2 : public ObjectTransformerBaseAbstractClass {
template <typename TStructure> TStructure ToStructure(std::vector<unsigned char> bytes) {
// some other implementation
}
template <typename TStructure>
std::vector<unsigned char> ToBytes(TStructure structure) {
// some other implementation
}
};
template <typename TStructure>
void coutStructureBytes(ObjectTransformerBaseAbstractClass *objectTransformerBaseAbstractClass, TStructure structure) {
// transform structure to bytes using the passed objectTransformerBaseAbstractClass object and cout it.
}
在我的基类中,我需要说“实现这些纯抽象泛型函数,它们接受不同类型的不同参数并在派生类中执行操作”。在我的派生类中,我需要实现这些接受不同类型参数的纯抽象泛型函数。
我不明白如何实现我想要的这个功能(你可以在上面的程序中看到,如果它编译和工作的话)。请推荐一个解决方案或解释如何使这项工作。
【问题讨论】:
-
"接受不同类型的参数" vs "不使用模板".???
-
提示:请将您的代码简化为仅显示问题所在的示例。您的示例方法中的所有内容实际上只是在浪费读者时间。一个简单的打印就足够了!请删除所有 memcpy/resize,bla 的东西,因为它与具有未知参数类型的抽象基类的问题无关......
-
@Klaus 好的,我将示例简化为仅基类和派生类,并且不包括实现。
标签: c++ abstract-class function-templates