tags:

views:

287

answers:

3

Hi, 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 :/

+5  A: 

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?

Naveen
+2  A: 

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.

anon
Template Meta Programming? That would be my guess.
Doug T.
Exactly, maybe I should have written it out :)
broken
This looks good Neil, I will test it right away!
broken
broken, you don't need to do this. You can just write 2.0/5 and the compiler will calculate it at compile time too.
rlbond
@broken - I wouldn't bother testing it - I don't think this can be classed as meta-programming!
anon
other than for pure fun or for learning purposes, is there any real use of this?
Naveen
I read the question as an over-simplified version of the actual question, so the answer is necessarily over-simplified too. Obviously it was useful to the OP.
Mark Ransom
+1  A: 

Here are some examples with template recursion.

Nick D
great link.