模板化递归数据类型 [英] templated recursive data types
问题描述
我有一个像这样的递归数据类型:
I have a recursive data type like this:
template<typename T>
struct SomeType {
std::map<T, SomeType<T>> mapping;
};
SomeType<int> foo;
这可以正常工作,但是由于类型不完整,将 std :: map
替换为 std :: unordered_map
会导致编译错误.我(或gcc)在某处出错吗?还是这只是标准的一部分?
This works fine, but replacing std::map
with std::unordered_map
results in a compile error due to an incomplete type. Am I (or gcc) making an error somewhere? or is this just part of the standard?
我还希望通过模板参数(例如 std :: stack
和 std :: queue
)确定内部容器,但我无法确定一种可行的方法,因为这将需要已定义SomeType.
I would also like to have the internal container determined by a template parameter (like std::stack
and std::queue
), but I can't figure out a way to do it since that would require SomeType to already be defined.
不完整的示例:
template<typename T, typename C = std::map<T, SomeType<[???]>>>
struct SomeType {
C mapping;
};
SomeType<int, [???]> foo;
我知道这可以通过运行时间接操作来完成,但这不是我想要的.
I know this can be done with runtime indirection, but that's not what I'm looking for.
推荐答案
您的课程在其定义的最后}
之前的任何地方都不完整.因此, mapping
成员在其类型的模板参数中使用了不完整的类型 SomeType
.
Your class is incomplete anywhere before the final }
of its definition. So the mapping
member is using incomplete type SomeType
in its type's template arguments.
该标准不允许这样做,而且很幸运,它可以与某些STL容器一起使用.
您的第二个问题属于相同的答案-首先这样做是违法的.
Your second questions falls under the same answer -- it is illegal to do that in the first place.
这篇关于模板化递归数据类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!