Static variable inside template function

前端 未结 7 1913
一向
一向 2020-12-14 07:10

In C++, if you define this function in header.hpp

void incAndShow()
{
  static int myStaticVar = 0;
  std::cout << ++myStaticVar << \" \" <<         


        
相关标签:
7条回答
  • 2020-12-14 07:35

    Templates are instantiated as needed, which means that compiler (linker as well in this case?) will make sure that you don't end up with multiple instances of the same template as well as only those instances of templates that you need - in your case only incAndShow<int>() is instantiated and nothing else (otherwise compiler would have to try to instantiate for every type which does not make sense).

    So I assume that the same methods it uses to figure out for which type to instantiate template prevents it from instantiating twice for the same type e.g. only one instance of incAndShow<int>()

    This is different from non template code.

    0 讨论(0)
提交回复
热议问题