Can I initialize a static const member at run-time in C++?

前端 未结 11 1087
小蘑菇
小蘑菇 2020-12-09 16:22

Is it possible to initialize a static const member of my class during run-time? This variable is a constant throughout my program but I want to send it as a command-line arg

11条回答
  •  星月不相逢
    2020-12-09 16:33

    Method #1: Initialize a hidden non-const variable, and provide a const reference to it (as shown by dasblinkenlight):

    class A {
    public: 
      static const int &T;
    };
    
    static int dummy = 0;
    const int &A::T  = dummy;
    
    int main() {
      dummy = 10;
      std::cout << A::T << std::endl;
    }
    

    Live Demo

    Method #2: Use a non const static member (as shown by R Sahu):

    class A {
    public: 
      static int T;
    };
    
    int A::T = 0;
    
    int main() {
      A::T = 10;
    }
    

    Live Demo

    Method #3: Declare a hidden non-const variable as a private static member of your class and provide a static member const reference to interface it. Define a friend function as inititalizer:

    class A {
      friend void foo(int);
        static int dummy;
    public: 
        static const int &T;
    };
    
    const int &A::T = A::dummy;
    int A::dummy = 0;
    
    void foo(int val) { A::dummy = val; }
    
    int main() {
        foo(10);
        std::cout << A::T << std::endl;
    }
    

    Live Demo

    Method #4: Declare a hidden non-const variable as a private static member of your class and provide a static member const reference to interface it. Define a static member function as inititalizer:

    class A {
        static int dummy;
    public: 
        static const int &T;
        static void foo(int val) { A::dummy = val; }
    };
    
    const int &A::T = A::dummy;
    int A::dummy = 0;
    
    int main() {
        A::foo(10);
        std::cout << A::T << std::endl;
    }
    

    Live Demo

    Bonus:

    If you want to initialize only once you can change the helper function to:

    static void foo(int val) { 
      static bool init = true;
      if(init) A::dummy = val;
      init = false;
    }
    

    Live Demo

提交回复
热议问题