我有一個基類,應該繼承幾個類。基類應該是一個簡單的介面,可以繼承它以便于實作/將資料傳遞到庫中。但是,被覆寫方法的引數因實作(繼承)而異。
在我的具體情況下,一個應該決議檔案的類和使用的檔案路徑(及其名稱)的數量因實作而異。
例子
這是一個最低限度的簡化示例,因為首先我不允許共享我的代碼,其次是為了更好地說明我的問題。
class Base
{
public:
Base() = default;
virtual ~Base() = default;
// this should be the interface method
virtual void fn() = 0;
};
class Child1: Base
{
public:
Child1() = default;
virtual ~Child1() = default;
// in this implementation three parameters are needed
virtual void fn(const std::string& file_path_1,
const std::string& file_path_2,
const std::string& file_path_3) override;
};
class Child2: Base
{
public:
Child2() = default;
virtual ~Child2() = default;
// in this implementation only two parameters are needed
virtual void fn(const std::string& file_path_1,
const std::string& file_path_2) override;
};
我已經嘗試過的
我已經嘗試使用 Variadic 引數,這在理論上是可行的。只有可讀性受到影響,并且不能保證在編譯時給出了所需數量的引數。
class Base
{
public:
Base() = default;
virtual ~Base() = default;
// this should be the interface method
virtual void fn(const std::string& file_pats, ...) = 0;
};
我也考慮過可變引數模板,但由于它的復雜性/實施作業很快就放棄了這種方法,以便找到更簡單的解決方案(但如果這是唯一可行的方法,請告訴我)。
問題
有沒有辦法擁有一個帶有純虛擬方法的抽象基類,其引數可能在不同的實作之間有所不同?
uj5u.com熱心網友回復:
在 C 中應避免使用 C 風格的可變引數函式。最好使用可變引數模板函式,但不幸的是,這對于虛函式并不真正起作用,請參閱這篇文章以了解原因。
@AdrianMole 和 @user17732522 暗示了正確的答案:嘗試找到一種方法將事物串列作為單個引數傳遞,可以是初始化串列或某些容器,如 a std::vector(或容器的視圖,例如使用 C 20 的std::span)。
最后,如果引數的數量真的取決于派生型別,那么也許fn()根本不應該是一個虛函式。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/496811.html
下一篇:Blazor組件類的繼承
