Violet Giraffe
Violet Giraffe

Reputation: 33627

Type-specific static declaration in a template function

I've just written the following snippet:

// Fix for MinGW 4.9.2 bug - std::log2 is missing there
template <typename T>
T log2 (T value)
{
    static const T l2 = std::log(T(2));
    return std::log(value) / l2;
}

Obviously, l2 should be unique for each T type because it is of type T. But does it actually work that way as per the C++ standard?

Upvotes: 0

Views: 48

Answers (1)

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 123548

Note that once instantiated

log2<double>

and

log2<float>

are two completely different functions. They both get their own static variable. After template instantiation, this is the same situation as if you had two functions:

double log2(double) {
    static double x;
    /*...*/
}

and

float log2(float) {
    static float x;
    /*...*/
}

This is also nicely explained here in an example around 6:00.

Upvotes: 2

Related Questions