9

static local variables of an inline function in C++ are guaranteed to exist as if being a single global variable, if my understanding is correct.

Does the same apply if the inline function is a template, where the compiler can generate multiple versions of the function?

  • There is now way to have a global `inline` variable in multiple libraries (or a template `inline` variable in multiple translation units). There is no standardized linking. –  Jun 01 '15 at 19:36
  • @DieterLücking Do you mean that the `inline` variable proposal was accepted to be included in the next standard? –  Jun 01 '15 at 19:41
  • @xiver77: No clue - can you provide a link –  Jun 01 '15 at 19:43
  • 1
    @DieterLücking You said "there is now way to have a **global inline variable** in multiple libraries". –  Jun 01 '15 at 19:46
  • 1
    A template function is not a function. It is a template for producing functions. Each set of template arguments (not function arguments) produces a distinct function. The rules around `inline` apply to each such function instance. Is that is what you are asking about? – Yakk - Adam Nevraumont Jun 01 '15 at 20:32
  • @shuttle87 A static member is very different from a local static. – Alan Stokes Jun 01 '15 at 21:26

1 Answers1

5

The following article should answer you question very well: http://www.geeksforgeeks.org/templates-and-static-variables-in-c/

In short: The Compiler produces one static variable for each template.

If you want to have the same variable for all templates you can maybe try something like this:

int& hack()
{
  static int i = 10;
  return i;
}

template <typename T>
void fun(const T& x)
{
  int &i = hack();
  cout << ++i;
  return;
}
Thomas Sparber
  • 2,827
  • 2
  • 18
  • 34