在 C++ 中运行时选择模板参数
假设我有一组函数和类,它们被模板化为使用单精度(float
)或双精度
。 当然,我可以只编写两段引导代码,或者弄乱宏。 但是我可以在运行时切换模板参数吗?
Suppose I have a set of functions and classes which are templated to use single (float
) or double
precision. Of course I could write just two pieces of bootstrap code, or mess with macros. But can I just switch template argument at runtime?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不,您无法在运行时切换模板参数,因为模板是由编译器在编译时实例化的。 您可以做的是让两个模板都派生自一个公共基类,始终在代码中使用基类,然后决定在运行时使用哪个派生类:
宏与模板有相同的问题,因为它们是在编译时扩展的。
No, you can't switch template arguments at runtime, since templates are instantiated by the compiler at compile-time. What you can do is have both templates derive from a common base class, always use the base class in your code, and then decide which derived class to use at runtime:
Macros have the same problem as templates, in that they are expanded at compile-time.
模板是一种编译时机制。 顺便说一句,宏也是如此(严格来说 - 一种预处理机制 - 甚至在编译之前就出现了)。
Templates are a compile-time mechanism. BTW, macros are as well (strictly speaking - a preprocessing mechanism - that comes even before compilation).
模板纯粹是编译时构造,编译器将扩展模板并使用指定的参数创建类/函数,并将其直接转换为代码。
如果您尝试在运行时在
foo
和foo
之间切换,您要么需要使用一些元编程技巧,要么只需要单独的代码路径每个。Templates are purely a compile time construct, the compiler will expand a template and create your class/function with the specified argument and directly translate that to code.
If you are trying to switch between
foo<float>
andfoo<double>
at runtime, you'll either need to use some metaprogramming trickery or just have seperate code paths for each.