[英]Use templated object within a templated class with different sets of template parameters
我正在嘗試在模板化 class 中使用模板化 object,其中 object 的模板參數與 object 所需的模板參數不同。 這聽起來有點混亂,因為沒有正確描述,這里有一個例子。
下面的 class 實現了一個二叉搜索樹:
template <typename KEY, typename VALUE>
class BST{
public:
BST(void){
cache = new GCACHE<uint64_t, BSTObject>(this);
}
struct{
string value;
}BSTObject;
GCACHE<uint64_t, BSTObject>* cache;
...
}
GCACHE class 實現了一個通用緩存,並且對於 function 正確它需要一個指向它必須緩存的 BST 的指針。 這個指針被傳遞給 GCACHE 構造函數:
template <typename CKEY, typename OBJECT>
GCACHE{
public:
GCACHE( *** pointer to BST, a templated class whoose template types that are not CKEY and OBJECT ***); (A)
}
如何在 (A) 中指定/定義一組與 GCACHE 所需的模板參數不同的模板參數(示例中為 CKEY 和 OBJECT)? GCACHE object 的模板參數是uint64_t
和BSTObject
,而 BST object 的模板參數可能是int
和string
。
我真的很困惑。 也許我弄錯了,解決方案很簡單......謝謝你的幫助。
我希望上面的例子足夠清楚以獲得幫助。 如果不是,請告訴我,以便我可以改寫這個問題。
GCACHE
需要訪問BST
的哪些部分?
如果它只需要訪問不依賴於模板參數KEY
和VALUE
的部分,則創建BST
實現的抽象接口 class ,並將該 class 用作GCACHE
構造函數的指針類型:
class BSTInterface {
...
};
template<typename KEY, typename VALUE>
class BST : public BSTInterface {
...
};
template <typename CKEY, typename OBJECT>
GCACHE{
public:
GCACHE(BSTInterface *bst); (A)
};
如果GCACHE
確實需要訪問依賴於模板參數的BST
部分,那么您還需要將GCACHE
模板化為這些參數:
template <typename CKEY, typename OBJECT, typename KEY, typename VALUE>
GCACHE{
public:
GCACHE(BST<KEY, VALUE> *bst); (A)
};
順便說一句,一般來說,類之間的這種循環依賴會產生緊密耦合,並且可能表明存在設計問題。 為什么“通用緩存”需要知道二叉搜索樹的存在? 或者,如果緩存被實現為樹,為什么樹實現需要知道緩存的存在?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.