在 C++ 中对任意长度的类型列表进行模板化;
这是我希望能够输入的内容:
class foo : public watchKeys<A, B, C> {}; //Or any list of keys
Boost::mpl 有序列,允许您执行此操作,但我不想必须这样做:
class foo : public watchKeys<mpl::list<A, B, C> > {};
我不介意它内部“丑陋”或冗长,但我希望 watchKeys 最终的使用方式非常简单直观。我也无法弄清楚 boost 是如何做到这一点的,但这似乎是因为我和模板之间有一层宏。
我该怎么办?我宁愿不为每种数量的类型做巨大的模板列表,但如果这是唯一的,那就是唯一的方法......
编辑:我已经相当确定没有办法做我想做的事(几乎,但你不能有可变数量的宏参数),但问题仍然产生有用且信息丰富的答案。
Here's what I want to be able to type:
class foo : public watchKeys<A, B, C> {}; //Or any list of keys
Boost::mpl has sequences, which allow you to do this, but I don't want to have to do:
class foo : public watchKeys<mpl::list<A, B, C> > {};
I don't mind it being "ugly" or verbose on the inside, but I want the way watchKeys is ultimately used to be very simple and intuitive. I also can't figure out how boost is doing it, but that seems to be because there's a layer of macros between me and templates.
How might I go about this? I'd prefer not to do the giant list of templates for each number of types, but if that's the only it's the only way...
Edit: I've become fairly certain that there's no way to do what I want to do (almost, but you can't have a variable number of macro arguments), but the question is still generating useful and informative answers.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
每种类型的巨大模板列表是当前版本的 C++ 中实现此目的的唯一方法。有关如何进行的示例,请参阅 boost::tuple。
C++0X 支持可变参数模板,但这还没有得到很好的支持(我认为现代版本的 GCC 虽然有实验性支持)。
The giant list of templates for each number of types is the only way to do it in the current version of C++. See boost::tuple for an example of how to go about.
C++0X supports variadic templates, but that isn't well supported yet (I think modern version of GCC have experimental support though).
或者你可以递归地执行
然后你可以像这样处理它
Alternatively you can do it recursively
You can then process it like this