C++ 中的类型数是多少?模板变体有限?
我试图了解变体是如何实现的,并阅读:
http://www. codeproject.com/KB/cpp/TTLTyplist.aspx
我的印象是我无法编写采用 X 类型的变体;但是模板编写者选择了一些 N,而我在变体中只能拥有少于 N 的类型。
这是正确的吗?
谢谢!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在 C++03 中,没有可变参数模板。这意味着是;你只需要选择一些 N 去完成,然后接受它。
在 C++0x 中,将有可变参数模板,因此您可以对所有 X 使用一个定义。
如果您希望轻松更改数字,可以使用 Boost.Preprocessor 并让它为您完成工作:
如果
MAXIMUM_TYPELIST_SIZE
如果是 5,这些宏将扩展到文章中的内容。(当然,如果您使用Boost,只需使用他们的 元编程库。)
In C++03, there are no variadic templates. This means yes; you simply have to pick some N to go up to, and live with that.
In C++0x, there will be variadic templates, so you could use one definition for all X.
If you're looking to make changing the number easy, you can use Boost.Preprocessor and have it do the work for you:
If
MAXIMUM_TYPELIST_SIZE
were 5, those macro's would expand to what the article has.(Of course, if you're using Boost just use their meta-programming library.)
是的——库的实现设置了一些限制。 IIRC,在 Loki 中默认最大值为 99。看了那篇文章,他将限制设置为 5,这可能足以完成大量工作,但我可以看到超过它的可能性;我无法想象超过 Loki 允许的 99 个(尽管在任何一种情况下,如果您愿意的话,扩展限制都是一项微不足道的编辑工作)。
Yes -- there's some limit set by the implementation of the library. IIRC, in Loki the maximum is 99 by default. Glancing at that article he's set the limit at 5, which is probably enough for a lot of work, but I can see the possibility of exceeding it; I can't quite imagine exceeding the 99 Loki allows (though in either case it's a trivial editing job to extend the limit if you want).
如果没有可变参数模板支持,模板作者只能提供看起来像可变参数模板的解决方法:
这里作者提供的模板参数数量是限制。
如果他们不提供这样的解决方法,您将被迫诉诸显式类型列表,相比之下,这相当笨拙:
这些不限于固定数量的类型,但不是我想显式使用的东西。
在下一个 C++ 标准中,这个问题将通过真正的可变参数模板来解决:
Without variadic template support, template authors can only provide workarounds that look like variadic templates:
Here the number of template arguments the author provides is the limit.
If they wouldn't provide such work-arounds, you'd be forced to resort to explicit typelists, which are quite clumsy in comparison:
These are not limited to a fixed number of types, but not something i'd like to use explicitly.
With the next C++ standard this will be solved with true variadic templates:
在现行标准下这是正确的;模板只能有固定数量的参数,库使用预处理器元编程等技术来模拟可变参数模板参数,直至达到某个设定的最大值。通常这在实践中不是什么大问题,因为最大值设置为远高于大多数人使用的值。
在新的 0x 标准中,支持真正的可变参数模板参数。
That is correct under the current standard; templates can only have a fixed number of arguments, and libraries use techniques like preprocessor meta-programming to simulate variadic template parameters up to a certain set maximum. Normally this isn't much of a problem in practice because the maximums are set such to be well above what most people use.
In the new 0x standard, there is support for true variadic template parameters.