[英]C++ template how to overloading operator and accessing private property
我目前正在嘗試實現一個簡單的基於模板的鏈表,它在C ++ 11中采用通用鍵/值對。 元素應該由+ =運算符添加到列表中。 代碼如下所示:
名單
// Forward declarations
template<typename K, typename V>
class list;
template<typename K, typename V>
list<K, V> &operator+=(list<K, V> &list, const std::tuple<K, V> ele) {
if (!list.head) {
// list is empty
list.head = new element(ele, nullptr);
}
return list;
};
// Class definition
template<typename K, typename V>
class list {
private:
struct element {
const K key;
const V value;
element *next;
element(const std::tuple<K, V> tuple, element *ele) :
key(std::get<0>(tuple)),
value(std::get<1>(tuple)),
next(ele) { }
};
element *head = nullptr;
public:
friend list<K, V> &operator+=<>(list<K, V> &list, const std::tuple<K, V> ele);
};
我無法編譯。 我是否必須將運算符的實現放入前向聲明或類本身? 如果我把它放在前向聲明中,就像在片段中一樣,我似乎無法使用“list.head = new element(ele,nullptr);”。 錯誤:'element'之前的預期類型說明符
如果我將它放入課堂本身,我就無法訪問list.head,即使它是朋友。
您應該在類模板定義之前(在前向聲明之后)保留函數模板的聲明,以告訴編譯器在friend聲明中指定的operator+=
是模板。 然后再定義它。 例如
// Forward declarations
template<typename K, typename V>
class list;
// declaration of function template
template<typename K, typename V>
list<K, V> &operator+=(list<K, V> &l, const std::tuple<K, V> ele);
// Class definition
template<typename K, typename V>
class list {
...
friend list<K, V> &operator+=<>(list<K, V> &l, const std::tuple<K, V> ele);
};
// definition of function template
template<typename K, typename V>
list<K, V> &operator+=(list<K, V> &l, const std::tuple<K, V> ele) {
if (!l.head) {
// list is empty
l.head = new typename list<K, V>::element(ele, nullptr);
}
return l;
}
PS:
不要使用名稱list
命名參數,該list
與類模板list
的名稱沖突。
element
是一個嵌套的struct,在operator+=
你應該像typename list<K, V>::element
一樣指定它。
使用名稱list
(與std::list
相同)不是一個好主意。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.