C++模板化地图包含自身
我有一个模板化类,可以将地图类型作为模板参数。
template<typename map_t> class my_class
{
map_t my_map;
};
现在我希望地图的值类型等于此类。
my_class<std::map<std::string, my_class<...> > > problems;
然而,这是不可能宣布的。我怎样才能达到同样的效果?
I have a templated class, that can have a map type as template parameter.
template<typename map_t> class my_class
{
map_t my_map;
};
Now I'd like the value type of the map, to be equal to this class.
my_class<std::map<std::string, my_class<...> > > problems;
However, this is impossible to declare. How can I achieve the same effect?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
由于您希望在容器类型中通用,因此我能够找到的最接近的(如果我很好地理解您的意图)是:
并使用
Since you want to be generic in the container type, the closest I have been able to find (if I understand well your intent) is:
and use
您尝试过吗?
如果您不将映射作为模板参数传递,而是将映射键、值和比较运算符作为模板参数传递,可能会更好
Have you tried this
It might be better if you don't pass the map as a template parameter and instead pass map key , value and comparison operator as template parameters
你不能这样做,因为它是无限递归的。您可以使用固定深度,或者必须通过继承、变体或类似的方式动态确定其中的值。
You can't do that, because it's infinitely recursive. You can do either a fixed depth, or you will have to use some dynamic determination of the values within via inheritance, a Variant, or something like that.
你不能那样做。
您可以做的最近的事情是奇怪的重复模板模式。
You can't do that.
The nearest thing you can do is Curiously recurring template pattern.
看起来你应该能够转发声明
my_class
并使用指向它的指针作为你的mapped_type
(在 C++ 中value_type
意味着一个对包括映射的键和值)。It seems like you should be able to forward declare
my_class<T>
and use a pointer to that as yourmapped_type
(in C++value_type
means a pair including both the key and value for maps).正如其他人指出的那样,您无法创建无限递归的类定义,但您当然可以嵌套
my_class
有限次数。这是一个工作示例:As others pointed out you cannot create an infinitely recursive class definition, but you can certainly nest
my_class
a finite number of times. Here's a working example:该类实际上不能包含自身作为成员(想想需要多少内存来包含它),但它可以包含一个指针指向自身。您可以使用引用的模式 J-16 SDiZ 或一些诱饵和开关来实现此目的:
The class can't actually contain itself as a member (think how much memory you'd need to contain it), but it can contain a pointer to itself. You can implement this using the pattern J-16 SDiZ cited, or some bait-and-switch: