Templates_use_of_static_variables

PHOTO EMBED

Thu Mar 10 2022 14:51:14 GMT+0000 (Coordinated Universal Time)

Saved by @gtsekas #c++

using namespace std;

template <class T> void f(T) {
  static int i = 0;
  cout << ++i;
}

int main() {
  f(1);
  f(1.0);
  f(1);
}
content_copyCOPY

The program is guaranteed to output: 112 Each function template specialization instantiated from a template has its own copy of any static variable. This means we get two instantiations of f, one for T=int, and one for T=double. Thus, i is shared between the two int calls, but not with the double call.

https://cppquiz.org/