0

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?

Violet Giraffe
  • 32,368
  • 48
  • 194
  • 335
  • 1
    did you try it? Why it should not work? each instantiation gets its own static variable – 463035818_is_not_an_ai Jul 15 '16 at 17:26
  • @tobi303: It struck me that in the nature of static declarations, it may be ONLY defined once (say, for whatever type instantiates it first). I can only try it with one compiler in the next couple days, but I'm actually writing cross-platform code here. – Violet Giraffe Jul 15 '16 at 17:28
  • no, it is defined ONLY once FOR EACH instantiation of the template. I had a link to a nice video with an example on that, maybe I will find it... – 463035818_is_not_an_ai Jul 15 '16 at 17:29
  • here is the [link](https://www.youtube.com/watch?v=WXeu4fj3zOs) (around 6:00) and [this](http://stackoverflow.com/questions/38059936/template-function-static-variable/38059959#38059959) is almost a dupe – 463035818_is_not_an_ai Jul 15 '16 at 17:30
  • 2
    [This](http://stackoverflow.com/a/14663369/241631) answers your question, even though that question is about something unrelated. – Praetorian Jul 15 '16 at 17:34
  • related: http://stackoverflow.com/questions/37345946/why-are-static-members-of-template-classes-not-unique. It is for classes but it has the same behavior with functions. – NathanOliver Jul 15 '16 at 17:43

1 Answers1

2

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.

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185