Defining constexpr static data members

前端 未结 3 742
广开言路
广开言路 2020-12-19 07:34

So, I\'m aware that in C++ static members can be initialized inside the class if they are a const literal type like the following

class test{
public:
               


        
3条回答
  •  自闭症患者
    2020-12-19 08:02

    C++17 inline variables

    In C++17 if you also mark the static member as inline, then I believe that you can odr-use it freely or have multiple definitions across compilation units, e.g.:

    #include 
    
    class MyClass {
        public:
            inline static constexpr int i = 42;
    };
    
    
    int main() {
        const int &cs = MyClass::i;
        std::cout << cs << std::endl;
        std::cout << &MyClass::i << std::endl;
    }
    

    More info at: How do inline variables work?

提交回复
热议问题