如何在需要每个集合具有相同签名的多组静态方法之间切换?自然的方式似乎实现了一个通用接口,但C ++中没有virtual static
方法。
答案 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() {};
};