Use integer template argument to create compiletime double

Assuming that your compiler supports C++14 or higher (which should be a valid assumption in the year 2019) this is very simple using a constexpr function:

constexpr double myPow(double x, int exp)
{
    double pow = 1.0;
    for (int i = 0; i < exp; ++i)
        pow *= x;
    for (int i = 0; i > exp; --i)
        pow /= x;
    return pow;
}

template < int exp >
struct DoubleValue
{
    static constexpr double value = myPow(10.0, exp);
};

See here to verify that it works and that even without optimization the value is generated at compile time.

Depending on your use case you might not even need the DoubleValue struct but can directly use myPow().


Update

As pointed out by @Bob__ in the comments, there may be better algorithms regarding numerical precision than the one presented here. But since C++14 many basic language features can be used in the body of a constexpr function. So, as long as you don't need any external library for it, you are free to implement whatever algorithm fits your needs.

Tags:

C++