gpt4 book ai didi

c++ - 如何允许子类具有公共(public)基类但在其方法中接受不同类型的参数

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

我希望标题最适合我的问题,但我会进一步解释。

我正在使用两种数据类型(一种由 Eigen 库支持的矩阵和一对由包含 int 值的字符串键入的 STL 映射)。

我想让我的代码尽可能通用地与它们一起工作。所以我开始创建一个抽象基类,包括我需要的基本操作(插入、获取“行”等)并尝试派生两个子类来包装我的数据类型(一个用于矩阵,一个用于我的对)实现内部函数正如我所需要的。

这在一段时间内运行良好,但随后我遇到了一些打字问题,因为我的矩阵由整数索引,而 HashMap 由字符串索引(它们都以不同的方式表示相同的数据类型)。当我试图编写检索“行”的代码时,我被卡住了,因为我知道我不能在我的基类中声明一个方法,然后用不同的参数类型覆盖它(矩阵通过数字索引和映射检索行通过字符串检索)。

是否有一种通用的方法可以在不过度使用每个子类的模板的情况下做到这一点?

一个代码示例可能会很清楚(原谅任何错误,因为这只是一个示例):

class BaseClass {
public:
virtual GenericRowType getRow(???? index)=0;
}

class MatrixWrapper : public BaseClass{
// Should be: GenericRowType getRow(int index);
}

class MapsWrapper : public BaseClass{
// Should be: GenericRowType getRow(string index);
}

最佳答案

您可以使用模板:

template <typename T>
class BaseClass {
public:
virtual GenericRowType getRow(T index)=0;
}

class MatrixWrapper : public BaseClass<int>{
// Should be: GenericRowType getRow(int index);
}

class MapsWrapper : public BaseClass<string>{
// Should be: GenericRowType getRow(string index);
}

关于c++ - 如何允许子类具有公共(public)基类但在其方法中接受不同类型的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22167496/

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