Maram
Maram

Reputation: 31

Template function with static variable

I have 2 functions with almost same impelementation so in order to optimise the code, We propose to create a template function.

Bellow just an example of the template function:

template<typename typo>
int func_test1(typo input)
{
   static int var;
   if (A)
   {
      var = input;
   }
   else if(B)
   {
      var = 1;
   }
   else
   {
      // do nothing
   }
   return var;
}

In case I called the template function created the first time and the condition A for example was true so the return value should be equal to input. If I call it the second time, and in case conditions A and B are not true, and since var is static is that mean it will keep the previous value?

I hope that my question is clear?

Upvotes: 0

Views: 81

Answers (1)

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 123439

func_test1 is a function template (not a template function, it is not a function). func_test1<Foo> and func_test1<Bar> are two distinct functions each with their own static variable, unless Foo is the same type as Bar.

Upvotes: 2

Related Questions