C++ Quiz53 of 173
Difficulty:
⬅️ Prev: 124Quiz ID: 125Next: 126 ➡️

According to the C++23 standard, what is the output of this program?

#include <iostream>

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

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

How many different instantiations of f will exist?

Reveal answer

112

Explanation

§[temp.fct.spec.general]¶2:

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.

⬅️ Prev: 124Quiz ID: 125Next: 126 ➡️