Overriding static variables when subclassing

后端 未结 8 447
南旧
南旧 2020-11-30 11:20

I have a class, lets call it A, and within that class definition I have the following:

static QPainterPath *path;

Which is to say, I\'m dec

8条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-30 11:57

    I know this question has been answered, but there is an other way to set the value of a similar static variable for multiple classes through a helper class and some template specialization.

    It doesn't exactly answer the question since it is not connected with subclassing in any way, but I've encountered the same issue and I found a different solution I wanted to share.

    Example :

    template 
    struct Helper {
      static QPainterPath* path;
      static void routine();
    }
    
    // Define default values
    template  QPainterPath* Helper::path = some_default_value;
    template  void Helper::routine { do_somehing(); }
    
    class Derived {};
    
    // Define specialized values for Derived
    QPainterPath* Helper::path = some_other_value;
    void Helper::routine { do_somehing_else(); }
    
    int main(int argc, char** argv) {
      QPainterPath* path = Helper::path;
      Helper::routine();
      return 0;
    }
    

    Pros:

    • clean, compile time initialization
    • static access (no instantiation)
    • you can declare specialized static functions too

    Cons:

    • no virtualization, you need the exact type to retrieve the information

提交回复
热议问题