从内部类访问外部公共成员



我有以下类,我正在尝试从内部类迭代器重载运算符*

#ifndef __LISTMAP_H__
#define __LISTMAP_H__
#include "xless.h"
#include "xpair.h"
template <typename Key, typename Value, class Less=xless<Key>>
class listmap {
public:
using key_type = Key;
using mapped_type = Value;
using value_type = xpair<const key_type, mapped_type>;
private:
Less less;
struct node;
struct link {
node* next{};
node* prev{};
link (node* next, node* prev): next(next), prev(prev){}
};
struct node: link {
value_type value{};
node (node* next, node* prev, const value_type&);
};
node* anchor() { return static_cast<node*> (&anchor_); }
link anchor_ {anchor(), anchor()};
public:
class iterator;
listmap(){};
listmap (const listmap&) = default;
listmap& operator= (const listmap&) = default;
~listmap();
iterator insert (const value_type&);
iterator find (const key_type&);
iterator erase (iterator position);
iterator begin() { return anchor()->next; }
iterator end() { return anchor(); }
bool empty() const { return begin() == end(); }
};

template <typename Key, typename Value, class Less>
class listmap<Key,Value,Less>::iterator {
private:
friend class listmap<Key,Value>;
listmap<Key,Value,Less>::node* where {nullptr};
iterator (node* where): where(where){};
public:
iterator(){}
value_type& operator*();
value_type* operator->();
iterator& operator++(); //++itor
iterator& operator--(); //--itor
void erase();
bool operator== (const iterator&) const;
bool operator!= (const iterator&) const;
};
template <typename Key, typename Value, class Less>
value_type& listmap<Key,Value,Less>::iterator<Key,Value,Less>::operator*()
{
return where->value;
}
#include "listmap.tcc"
#endif

问题是value_type是类列表映射中的公共成员,它不是静态的,所以我不知道如何完成运算符*((的声明。我不想通过更改代码结构来修复该错误。 例如:制作

using value_type = xpair<const key_type, mapped_type>;

全球。我只是想知道是否有其他技巧可以用来访问value_type。

....编辑:我不知道内部类如何识别value_type

它与迭代器几乎不同,您只需添加typename关键字即可

typename listmap<Key,Value,Less>::value_type

static性对于类型来说并不重要。

迭代器内部的别名1

template <typename Key, typename Value, class Less>
class listmap<Key,Value,Less>::iterator {
...
using value_type = typename listmap<Key,Value,Less>::value_type;
};

允许您使用自动后缀类型更简洁地编写定义:

template <typename Key, typename Value, class Less>
auto listmap<Key,Value,Less>::iterator::operator*() -> value_type&
{
return where->value;
}

注意:内部iterator类不是模板,只有listmap是:

listmap<Key,Value,Less>::iterator<Key,Value,Less>::operator
//                               ~~~~~~~~~~~~~~~~ remove this

1顺便说一句,不要忘记其他人。

最新更新