简体   繁体   中英

Floating point arithmetic at compile-time

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;
}

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: ie 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 ...

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.)

您应该等待带有C ++ 0x constexpr关键字实现的gcc 4.6。

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.

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 #include s it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM