我想要两个相互指向的结构。具体来说,我想要以下内容:
template<typename Key, typename Value>
class MyStructure {
public:
typedef map<Key, list<pair<Value, typename ListType::iterator>>> MapType;
typedef list<typename MapType::element_type::iterator> ListType;
private:
MapType map_;
ListType list_;
}
显然这不会起作用,因为 ListType 之前没有声明为类型。我怎么能这样做呢?正如您所看到的,我使用迭代器类型作为指向这两个结构元素的指针。
我正在考虑使用奇怪的重复模板模式,但没有取得任何进展。 ##c++ 上的有人也建议使用模板别名,但这也失败了(至少,我不知道如何使用这个想法)。
我在概念上做错了什么吗?或者也许“不符合C++概念”?我当然可以用 void*s 做到这一点,但我正在尝试以正确的方式做事:)
谢谢!
最佳答案
虽然我怀疑这可能是重复的(而且在很多方面都是重复的),但“干杯和 hth。 - Alf”正确地指出,潜在的重复问题专门与 typedef 的使用有关。
对于这种事情。
但是,在当前问题中,OP 想知道如何在问题中描述的场景中一般处理相互包含。
这里有一个建议:
#include <list>
#include <map>
template <typename Key, typename Value>
class MyElement;
template <typename Key, typename Value>
class MyStructure
{
public:
typedef std::map<Key,MyElement<Key,Value> > MapType;
typedef std::list<MyElement<Key,Value> > ListType;
};
template <typename Key, typename Value>
class MyElement {
public:
typename MyStructure<Key,Value>::MapType::iterator map_iterator;
typename MyStructure<Key,Value>::ListType::iterator list_iterator;
};
如您所见,我引入了一种新的数据类型 MyElement
,其中包含列表迭代器和 map 迭代器。因为这是一个类而不是 typedef,所以它可以被前向声明。
关于C++ 相互模板依赖?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9614464/