C++ static template member, one instance for each template type?

后端 未结 4 1401
长情又很酷
长情又很酷 2020-11-29 10:16

Usually static members/objects of one class are the same for each instance of the class having the static member/object. Anyways what about if the static object is part of a

4条回答
  •  甜味超标
    2020-11-29 11:04

    Static members are different for each diffrent template initialization. This is because each template initialization is a different class that is generated by the compiler the first time it encounters that specific initialization of the template.

    The fact that static member variables are different is shown by this code:

    #include 
    
    template  class Foo {
      public:
        static int bar;
    };
    
    template 
    int Foo::bar;
    
    int main(int argc, char* argv[]) {
      Foo::bar = 1;
      Foo::bar = 2;
    
      std::cout << Foo::bar  << "," << Foo::bar;
    }
    

    Which results in

    1,2
    

提交回复
热议问题