Floating point arithmetic at compile-time

我只是一个虾纸丫 提交于 2019-12-11 01:13:50

问题


Are floating point calculations, which use compile-time constant integers, performed during compile-time or during run-time? For example, when is the division operation calculated in:

template <int A, int B>
inline float fraction()
{
    return static_cast<float>(A) / B;
}

回答1:


I believe it is implementation defined, but most compilers will evaluate constant expressions at compile time. However even if yours does not the following modification:

template <int A, int B>
inline float fraction()
{
    static const float f = static_cast<float>(A) / B;
    return f ;
}

will at least ensure that the expression is evaluated just once if it is evaluated at runtime.




回答2:


For something this simple, the compiler will probably do it at compile time. In fact, the compiler will probably do it at compile time even without templates, as long as all the values are known at compile time: i.e. if we have inline float fraction(int A, int B), it will probably do the division at compile time if we call fraction(1,2) .

If you want to force the compiler to do stuff at compile-time, you will have to use some template metaprogramming tricks, and I'm not sure you can get it to work with floating-point arithmetic at all. But here is a basic example of the technique:

// Something similarly simple that doesn't use floating-point ;)
template <int A, int B>
struct Product {
    enum { value = A * B };
};

// Later:
... Product<3, 4>::value ...



回答3:


You should wait for gcc 4.6 with C++0x constexpr keyword implementation.




回答4:


Your best bet is to look at the generated code - there is no guarantee that floating-point operations will be performed at compile time, but at higher optimisation levels they potentially could be, particularly for something simple like this.

(Some compilers might avoid doing this because for some architectures the floating point behaviour is configurable at runtime. The results for the operation performed at compile time could then potentially differ from those from the same operation performed at runtime.)




回答5:


Neither the C or C++ standards require that constant expressions of any stripe be evaluated at compile time, but they do allow it. Most compilers released in the last 20 years will evaluate arithmetic expressions, so if not incurring a function call or inlining the code is important, keep it as simple as possble.

If the scope of these expressions is limited to a single file, you can always take advantage of the preprocessor and #define FRACTION(a,b) (float(a)/float(b)) for convenience. I don't recommend doing this in a header unless you have a good scheme to prevent polluting any file that #includes it.



来源:https://stackoverflow.com/questions/4417155/floating-point-arithmetic-at-compile-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!