Defining constexpr static data members

前端 未结 3 741
广开言路
广开言路 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 <iostream>
    
    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?

    0 讨论(0)
  • 2020-12-19 08:09
    static constexpr int stc = 1; // declares the static var
    
    constexpr int test::stc; // defines the static var
    

    for more detailed explanation check link below

    http://www.learncpp.com/cpp-tutorial/811-static-member-variables/

    0 讨论(0)
  • 2020-12-19 08:16

    In

    int main() { const int &cs = test::stc; } 
    

    test::stc is odr-used while in

    int main () {int array[test::stc];}  
    

    it is not.

    The following example from the C++11 Standard supports the above idea.

    struct S { static const int x = 0; };
    const int &f(const int &r);  
    int n = b ? (1, S::x)    // S​::​x is not odr-used here
              : f(S::x);     // S​::​x is odr-used here, so a definition is required
    

    Looking at it from practical point of view, cs will be an invalid reference unless test::stc has an address. array, on the other hand, needs just the value of test::stc, which can be evaluated at compile time. array does not need the address of test::stc to be a valid object.

    An object that is odr-used must be defined exactly once in a program.

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