How to force a static member to be initialized?

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

Consider this example code:

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

template
struct Foo{
           


        
5条回答
  •  萌比男神i
    2020-11-27 06:08

    We can use a simple trick based on a declaration that must be instantiated with the class:

    template<…>
    struct Auto {
      static Foo foo;
      static_assert(&foo);
    };
    template<…> Foo Auto::foo=…;
    

    Note that some compilers warn about the comparison to null; that can be avoided with &foo==&foo, (bool)&foo, or ((void)&foo,true) if needed.

    Note also that GCC 9.0–9.2 don’t count this as an odr-use.

提交回复
热议问题