我有兩個類,DynamicCollection
和Dictionary
。 Dictionary
繼承自DynamicCollection
並且這兩個類都是模板。外觀像這樣:模板類依賴項問題
template <typename ValueType>
class DynamicCollection;
template <typename KeyType, typename ValueType>
class Dictionary : public DynamicCollection<KeyValuePair<KeyType, ValueType>>;
我遇到的問題是,DynamicCollection
需要有一種方法GroupBy
,其申報如下:
template <typename Selector>
Dictionary<Selector, ICollection<ValueType>*>* GroupBy(std::function<Selector(ValueType)> evaluator);
所以我遇到的問題是循環依賴,我不知道如何重寫這個,所以它的工作原理。我已經嘗試着在DynamicCollection
頭聲明Dictionary
,然後定義在Dictionary
頭的方法,但後來我來到這個奇怪的情況:
template <typename Selector>
Dictionary<Selector, ICollection<ValueType>*>* DynamicCollection::GroupBy(std::function<Selector(ValueType)> evaluator);
但是,正如你可以猜測,DynamicCollection
需要一個模板參數列表以及函數對象的ValueType
(以及返回中的ICollection
)需要爲DynamicCollection
聲明中的ValueType
。所以,這顯然是錯誤的代碼,但我覺得它會是這樣的(如果我有在Dictionary
頭將它定義):
template <typename ValueType>
template <typename Selector>
Dictionary<Selector, ICollection<ValueType>*>* DynamicCollection<ValueType>::GroupBy(std::function<Selector(ValueType)> evaluator);
因爲當我把它定義是這樣的:
template <typename ValueType, typename Selector>
Dictionary<Selector, ICollection<ValueType>*>* DynamicCollection<ValueType>::GroupBy(std::function<Selector(ValueType)> evaluator);
我得到一個錯誤說,它不能找到匹配的聲明(其中排序對我來說很有意義)。
所以我的問題是:如何正確聲明和定義此方法?
您是否嘗試根據需要向前聲明模板類? –