如何用C ++实现虚拟静态行为?

时间:2016-12-06 18:48:31

标签: c++

如何在需要每个集合具有相同签名的多组静态方法之间切换?自然的方式似乎实现了一个通用接口,但C ++中没有virtual static方法。

1 个答案:

答案 0 :(得分:3)

您可以将static属性提升为单个实例并使用模板:

 template<typename Derived>
 class StaticInterface {
 protected:
      StaticInterface() {}
 public:
      virtual ~StaticInterface() {}
      static Derived& instance() {
           Derived theInstance;
           return theInstance;
      }

      // The interface:
      virtual void foo() = 0;
      virtual void bar() = 0;
 };

并使用

 class DervivedA : public StaticInterface<DerivedA> {
      template<typename Derived>
      friend class StaticInterface<Derived>;
      DerivedA() {}
 public:
      virtual void foo() {};
      virtual void bar() {};
 };

 class DervivedB : public StaticInterface<DerivedB> {
      template<typename Derived>
      friend class StaticInterface<Derived>;
      DerivedB() {}
 public:
      virtual void foo() {};
      virtual void bar() {};
 };

或者完全省略virtual部分(并创建&#34;昂贵的&#34; vtable):

 template<typename Derived>
 class StaticInterface {
 protected:
      StaticInterface() {}
 public:
      ~StaticInterface() {}
      static Derived& instance() {
           Derived theInstance;
           return theInstance;
      }

      // The interface:
      void foo() {
          Derived::foo_impl();
      }
      void bar() {
          Derived::bar_impl();
      }
 };

 class DervivedA : public StaticInterface<DerivedA> {
      template<typename Derived>
      friend class StaticInterface<Derived>;
      DerivedA() {}
 public:
      void foo_impl() {};
      void bar_impl() {};
 };