开发者

Dynamic typedef of a primitive in C++

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 recompil开发者_如何学Goe. 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.


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.


As @Kerrek SB points out, I'm not sure there's that much advantage to using floats over doubles.

I can't say definitively without seeing your code, but you might be able to do what you want with templates.

template <typename T>
T Crunch1(T rhs)
{
    // do something with 'rhs' and return the result
}
template <typename T>
T Crunch2(T lhs, T rhs)
{
    // do something with 'lhs' & 'rhs' and return the result
}

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜