Sunday, June 9, 2013

C++11 no floats in templates??? WTF???

Sigh... i have no idea why c++11 doesn't allow floats in templates...

template <float number>
struct Value
{
  static const float VALUE = number;
};

The crazier part is that they have allowed enough other syntax sugar that you can fake it.. So why not just support it in the first place??

#include <iostream>

template <int NUM, int DEN>
struct Float
{
    constexpr static float value() { return (float)NUM / (float)DEN; }
    static constexpr float VALUE = value();
};

template <class GRAD, class CONST>
struct LinearFunc
{
    static float func(float x) { return GRAD::VALUE*x + CONST::VALUE; }
};

int main()
{
    // Y = 0.333 x + 0.2
    // x=2, y=0.866
    std::cout << " func(2) = "
              << LinearFunc<Float<1,3>, Float<1,5> > ::func(2) << std::endl;
}