How can Derived class inherit a static function from Base class?

前端 未结 3 1263
旧巷少年郎
旧巷少年郎 2020-12-08 15:02
struct TimerEvent
{
   event Event;
   timeval TimeOut;
   static void HandleTimer(int Fd, short Event, void *Arg);
};

HandleTimer needs to be stat

3条回答
  •  执念已碎
    2020-12-08 15:23

    To some extent the traits pattern lets you inherit and redefine static methods.

    First start with a base class:

    struct base {
      static void talk()  { std::cout << "hello" << std::endl; }
      static void shout() { std::cout << "HELLO !!" << std::endl; }
    };
    

    Then derive it and redefine some methods:

    struct derived: public base {
      static void talk()  { std::cout << "goodbye" << std::endl; }
    };
    

    And now call the methods via a traits class:

    template < class T >
    struct talker_traits {
      static void talk() { T::talk(); }
      static void shout() { T::shout(); }
    };
    
    talker_traits::talk()     // prints "hello"
    talker_traits::shout()    // prints "HELLO !!"
    
    talker_traits::talk()  // prints "goodbye"
    talker_traits::shout() // prints "HELLO !!"
    

    ideone demo

    The traits class lets you reuse the static method base::shout while "overriding" base::talk with derived::talk. Still, there are several difference with actual inheritance:

    • The function to call is resolved at compile time
    • The child method needs not have the same signature as the parent one

    It works with static fields and typedefs too, the best example is std::iterator_traits.

提交回复
热议问题