有没有一种方法可以使成员在所有派生 类 中成为静态成员?

Is there a way to declare a member in a way that will make it static in all derived classes?

我有几个抽象的 classes 需要管理包含指向它们自身每个实例的指针的静态向量。下面是其中一个 classes 的简化示例:

class AbstractBase1
{
public:
    AbstractBase1()
    {
        allInstances_.push_back(this);
    }
    AbstractBase1(const AbstractBase1& source)
      : AbstractBase1()
    {
        //Copy data from source
    }
    AbstractBase1(const AbstractBase1&& source)
      : AbstractBase1()
    {
        //Copy data from source
    }
    virtual ~AbstractBase1()
    {
        //Find the index of 'this' with std::find and remove it from allInstances_
    }
    virtual void purelyVirtualMethod() = 0;
    static void doSomethingWithAllInstances()
    {
        for (AbstractBase1* ptr : allInstances_)
        {
            ptr->purelyVirtualMethod();
        }
    }
private:
    static std::vector<AbstractBase1*> allInstances_;
    //Some data that will be inherited
};

因此,不必为每个需要此功能的 class 编写所有代码,我想我会创建一个包含此功能的 InstanceTracker class,然后让所有这些 classes 继承自它。 但是我无法理解这个 InstanceTracker class 的外观,因为我不希望这个 class 管理其所有派生的 classes' 实例的静态向量。我想要的是每个从 InstanceTracker 继承的 class 都将获得自己的静态向量来管理其实例。

有没有办法实现这个,还是我只需要为每个需要它的 class 编写实例跟踪代码?

您可能会使用模板:

template <typename Tag>
class AbstractBaseT
{
public:
    AbstractBaseT() { allInstances_.push_back(this); }
    AbstractBaseT(const AbstractBase1& source) : AbstractBaseT()
    {
        //Copy data from source
    }
    AbstractBaseT(AbstractBaseT&& source) : AbstractBase1()
    {
        //Move data from source
    }
    virtual ~AbstractBaseT()
    {
        //Find the index of 'this' with std::find and remove it from allInstances_
    }
    virtual void purelyVirtualMethod() = 0;
    static void doSomethingWithAllInstances()
    {
        for (AbstractBase1* ptr : allInstances_)
        {
            ptr->purelyVirtualMethod();
        }
    }
private:
    static std::vector<AbstractBaseT*> allInstances_;
    //Some data that will be inherited
};

然后

using AbstractBase1 = AbstractBaseT<struct tag1>;

或者 CRTP 方式也可能有用:

struct AbstractBase2 : AbstractBaseT<AbstractBase2>
{
    // ...
};