简体   繁体   中英

Calculate float at compile-time using templates

I'm new to this whole Template Metaprogramming in C++ mess and I simply can't get this right.

The scenario: For example, I've got fractions 2/5, 6/9,... I want to calculate the result of those fractions at compile-time and sort them later using that value at run-time.

Is this even possible? Macros maybe?

Edit: Thanks Naveen, but it doesn't answer the question if it's possible to calculate floats at compile time using templates. Using recursion, for example.

I can't find any info on the webs :/

You don't require templates for that. Any decent compiler will optimize the calculations when you do something like this: float f = 2.0/5; BTW, if all are compile time variables why do you want to sort them at run time?

Not sure what you are asking. Do you mean something like this:

#include <iostream>
using namespace std;;

template <int a, int b> struct Fract {
    double value() const {
        const double f = a / double(b);
        return f;
    }
};

int main() {
    Fract <2,5> f;
    cout << f.value() << endl;
}

Edit: If you seriously want to get into template programming, meta or otherwise, I strongly suggest getting hold of the book C++ Templates: The Complete Guide , which is excellent.

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