[英]How to allow subclasses to have a common base class but accept different types of arguments in their methods
我希望標題最適合我的問題,但我會進一步解釋。
我有兩種正在使用的數據類型(Eigen庫支持的Matrix和一對由保存int值的字符串作為鍵的STL映射)。
我希望我的代碼盡可能通用地與它們一起使用。 因此,我首先創建了一個抽象基類,其中包括我需要的基本操作(插入,獲取“行”等),並嘗試派生兩個子類來包裝我的數據類型(一個用於矩陣,一個用於我的線對),以實現內部功能根據我的需要。
這段代碼工作了一段時間,但隨后遇到了一些鍵入問題,因為我的矩陣由整數索引,而哈希映射由字符串索引(它們都以不同的方式表示相同的數據類型)。 當我嘗試編寫檢索“行”的代碼時,我被困住了,因為我知道我無法在基類中聲明一個方法,然后用不同的參數類型覆蓋它(矩陣通過數字索引和映射檢索行)通過字符串檢索它)。
有沒有一種通用的方法可以在不為每個子類過度使用模板的情況下進行此操作?
一個代碼示例可能會使您很清楚(原諒所有錯誤,因為這只是一個示例):
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);
}
這是使用模板的經典案例。 您應該使用一個類模板參數使BaseClass
成為模板,然后繼承的類將繼承為模板特化:
template <class T>
class BaseClass {
public:
virtual GenericRowType getRow(T index) = 0;
};
class MatrixWrapper : public BaseClass<int> {
public:
GenericRowType getRow(int index);
};
class MapsWrapper : public BaseClass<std::string> {
public:
GenericRowType getRow(std::string index);
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.