C++ 中原语的动态 typedef
我正在制作一个玩具物理引擎,它使用我称之为实数的浮点数。
目前,我使用的是 typedef;
typedef float real;
这样我就可以将浮点值的精度更改为双精度或长双精度,但显然我必须重新编译。我希望能够在运行时清晰地定义 real 的类型,以便我可以通过命令行或初始化 GUI 界面指定精度。
我知道 typedef 是在编译时确定的,所以我想知道是否有人有任何巧妙的想法。
I am making a toy physics engine which works with floating point numbers which I call reals.
At present, I am using a typedef;
typedef float real;
This is so I can change the precision of the floating point values to doubles or long doubles, but obviously I have to recompile. I would like to be able to cleanly define the type of real at runtime, so that I can specify the precision via command-line or an intialization GUI interface.
I know typedef is determined at compile time, so I am wondering if anyone has any neat ideas.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
浮点型比双精度型使用更少的内存,并且精度较低。
但是,只有一组数学库,并且它是基于双精度的。所有浮点数都会转换为双精度以进行计算,然后必须转换回浮点数。
只需使用双打即可。
A float uses less memory than a double and is less precise.
BUT, there is only one set of math libraries and it is double based. All floats get converted to double for calculations and then must be cast back to float.
Just use doubles.
正如 @Kerrek SB 指出的那样,我不确定使用
float
比使用double
是否有那么大的优势。如果没有看到您的代码,我不能明确地说,但您也许可以使用模板做您想做的事情。
这仍然是编译时多态性而不是运行时多态性,但可能是最接近您想要的东西。
而且,您可以创建一系列插件(每个所需的精度一个)并在运行时按照您建议的方式进行选择。每个插件都是特定精度的模板代码的实例。模板和插件架构的组合将为您提供所需的灵活性,而不会出现您显然试图避免的代码重复。
As @Kerrek SB points out, I'm not sure there's that much advantage to using
float
s overdouble
s.I can't say definitively without seeing your code, but you might be able to do what you want with templates.
This is still compile-time rather than runtime polymorphism but may be the closest thing to what you want.
And, you could create a series of plugins (one for each desired precision) and select that at runtime the way you suggest. Each plugin would be an instantiation of the template code for a particular precision. The combination of templates and a plugin architecture would give you the flexibility you want without the code duplication that you're obviously trying to avoid.