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?

6
  • 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. Commented Jun 1, 2015 at 19:36
  • @DieterLücking Do you mean that the inline variable proposal was accepted to be included in the next standard? Commented Jun 1, 2015 at 19:41
  • @xiver77: No clue - can you provide a link Commented Jun 1, 2015 at 19:43
  • 1
    @DieterLücking You said "there is now way to have a global inline variable in multiple libraries". Commented Jun 1, 2015 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? Commented Jun 1, 2015 at 20:32

1 Answer 1

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;
}
Sign up to request clarification or add additional context in comments.

Comments