Say that I have a C++ class with some fields with static storage duration, call it class A.

Is there some way to use inheritance to "inject" these static fields into classes which derive from class A? That is to say, if class B and class C derive from A, B and C will have the same static fields as the base class A, shared with all other instances of B and C, but operations on these fields within instances of B and C will be distinct to their respective subclasses, and not affect each other.

有帮助吗?

解决方案

No, and from the theoretical view of how inheritance works, it wouldn't make sense.

However, if you are using inheritance only for implementation purposes, templating the base class on the derived class would make that work, but then the various classes no longer share a common ancestor.

template <typename Derived>
class A { protected: static int count; };
class B : private A<B> { public: B() { ++count; } };
class C : private A<C> { public: C() { ++count; } };
许可以下: CC-BY-SA归因
scroll top