How to force a static member to be initialized?

后端 未结 5 1561
悲&欢浪女
悲&欢浪女 2020-11-27 05:46

Consider this example code:

template
char register_(){
    return D::get_dummy(); // static function
}

template
struct Foo{
           


        
5条回答
  •  眼角桃花
    2020-11-27 06:11

    Consider:

    template struct value { };
    
    template
    struct HasStatics {
      static int a; // we force this to be initialized
      typedef value value_user;
    };
    
    template
    int HasStatics::a = /* whatever side-effect you want */ 0;
    

    It's also possible without introducing any member:

    template struct var { enum { value }; };
    typedef char user;
    
    template
    struct HasStatics {
      static int a; // we force this to be initialized
      static int b; // and this
    
      // hope you like the syntax!
      user :var::value,
           :var::value;
    };
    
    template
    int HasStatics::a = /* whatever side-effect you want */ 0;
    
    template
    int HasStatics::b = /* whatever side-effect you want */ 0;
    

提交回复
热议问题