以下是我正在嘗試完成的操作:C++ 11非模板化基類中的純虛擬'模板化'返回類型
我試圖創建各種類型的鏈接列表。爲了做到這一點,我認爲多態是一個很好的方法。
我有兩個類,AttributeBase和Attribute。 AttributeSet使用AttributeBase,它只存儲屬性<T>(作爲AttributeBase *)的鏈接列表的開始和結束點,並對列表進行修改。 AttributeBase是屬性<T>的基類,僅在設計中用於製作泛型指針。屬性<T>當然是存儲實際值的特定類型的AttributeBase。每個屬性<牛逼>的主要數據是一種遺傳性的字符串(屬性的名稱,或者「關鍵」如果你願意)和類型T的值
所以,我迄今(簡體):
class AttributeBase
{
public:
AttributeBase() = delete;
AttributeBase* GetNext() { return next; };
AttributeBase* GetPrev() { return prev; };
std::string GetName() { return name; };
//Sometimes I need to get/set the value stored in a derived class
//But, how would I define the function here since the return
//type is of type T as defined in Attribute?
virtual ???? GetValue = 0;
virtual void SetValue(????) = 0;
friend class AttributeSet;
private:
AttributeBase* next = nullptr;
AttributeBase* prev = nullptr;
std::string name;
};
template <class T>
class Attribute : public AttributeBase
{
public:
Attribute(std::string _name, T _value){ name = _name; value = _value };
T GetValue(){ return value; };
void Setvalue(T){ value = T; };
private:
T value;
};
class AttributeSet
{
public:
template <class T>
void Add(std::string,T); //Add an Attribute<T>(std::string,T) to the list
void Delete(std::string);
bool Contains(std::string _name); //Scan the list to determine if an
//attribute with name of _name exists
template <class T>
T Get(std::string); //Scan the list for 'name' and return
//AttributeBase*->GetValue()
private:
AttributeBase* start = nullptr;
AttributeBase* end = nullptr;
}
因爲我試圖保持AttributeBase的泛型和非模板化(以避免在AttributeSet中強類型的開始和結束指針),這就產生了一個問題。如何爲虛函數BaseAttribute :: GetValue()指定一個尚未指定的返回類型。我第一次嘗試使用auto
,得到了一個編譯錯誤。
由於沒有實際的AttributeBase實例被創建(並且默認構造函數被刪除),我認爲可以省略GetValue並在派生類中定義它。但是,如果我嘗試* AttributeBase-> GetValue()它錯誤了,因爲GetValue()沒有在AttributeBase中定義,只有子類。你會認爲編譯器會知道指針必須指向派生類(唯一的派生類型),因爲不能直接構造AttributeBase。
因此,爲了使用GetValue(),我必須提前知道前一個值的類型,才能將AttributeBase *轉換爲Attribute *。如果AttributeBase本身是模板化的,並且包含一個值T型,這將是微不足道的。然後我可以訪問AttributeBase * - > type來確定我需要投射的指針的類型。然而,正如我所說的,模板AttributeBase破壞了對象的預期用途。
更可能的是,我以完全錯誤的方式(再一次)討論這個問題。但是在這一點上,我堅持想法。任何幫助,將不勝感激!
您可以舉一個使用'AttributeBase :: GetValue'或'AttributeBase :: SetValue'的代碼示例嗎? – aschepler