字符串化和取消字符串化模板参数
假设我有很多类在命名中带有“*Pack”对应项。例如,如果我有一个类 Moo,我就有 MooPack,如果我有 Foo,我也有 FooPack。
我想要一个 C++ 模板化函数,它从 Foo 返回 FooPack
template <class X, class XPack>
XPack packify(X input){
...
}
是否可以在不必指定模板参数的情况下执行此操作?目前,必须按如下方式完成:
Moo moo;
MooPack mooppey = packify<Moo, MooPack>(moo);
如果它只需要 Moo 模板参数,那么丑陋的模板规范位可能会消失,但除了使用 #defines(这也不是真正的最佳解决方案)之外,仍然没有不要这样做。
有办法吗,还是我必须等待c++0x?
suppose I have a lot of classes with their "*Pack" counterparts in naming. For example, if I have a class Moo, I have MooPack, if I have Foo, I also have FooPack.
I want to have a c++ templated function which returns a FooPack from a Foo
template <class X, class XPack>
XPack packify(X input){
...
}
Is it possible to do this without having to specify the template argument? At the moment, this has to be done like the following:
Moo moo;
MooPack mooppey = packify<Moo, MooPack>(moo);
If it only required the Moo template argument, that ugly template specification bit could go away, but apart from using #defines, which isn't really the best solution either, still doesn't do it.
Is there a way, or will I have to wait for c++0x?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你不必指定 Moo,只需指定 MooPack,因为 moo 会为你推导出参数。不过,我建议您在 Moo 本身内部将 MooPack 设为 typedef 或嵌套类(称为 Pack),在这种情况下,您可以通过模板内的类型名 X::Pack 轻松访问它。
You don't have to specify Moo, just MooPack, because moo will deduce the argument for you. However, I'd suggest that you make MooPack a typedef or nested class (called Pack) inside Moo itself, in which case you can easily access it by typename X::Pack inside the template.
正如 DeadMG 的答案已经提到的,您不需要显式指定参数类型,因为它可以自动推导(如果它是第二个而不是第一个模板参数)。既然你说你不能改变类型声明来形成类之间的链接,我会为此建议特征路线(想想std::iterator_traits):
这样你就可以调用函数而无需手动指定模板参数,而不需要修改类本身。
As the answer by DeadMG already mentioned you don't need to explicitely specify the parameter type as it can be deduced automaticaly (if it's the second instead of the first template parameter). Since you said you can't change the type declarations to form a link between the classes, I would propose the traits route for that (think std::iterator_traits):
This way you can call the function without manually specifying template arguments, without needing to modify the classes themselves.