C ++ using static array in base class, declaration in derived class

I am trying to create several classes, all of which are derived classes from an abstract class (let's call it) BaseClass. In BaseClass, I want to work with static variables (arrays) declared in derived classes. Is there a smart way in C ++ so that the compiler knows that a static variable will be declared in the class that received the top class? Or should I, for example, in the constructor of derived classes pass a reference to a static variable on the construction of the base class? This is my idea:

class BaseClass
{
   std::vector<float> &vector;

public:
   BaseClass(std::vector<float> &dVector):vector(dVector){};

   void vectorOperation()
   {
       vector.doSomething();
   }
   ...     
}

class DerivedClass : public BaseClass
{
   static std::vector<float> sVector;
   DerivedClass():BaseClass(sVector){};
   ... 
}

Is my decision right? Is there a better way to do this?

+4
2

BaseClass (), .

, . ( , ).

, , ?

. , .

, , :

class BaseClass
{
protected:
   virtual std::vector<float>& vector() = 0;

public:
   void vectorOperation()
   {
       vector().doSomething();
   }
   ...     
};

class DerivedClass : public BaseClass
{
   static std::vector<float> sVector;
protected:
    std::vector<float>& vector() { return sVector; }
   ... 
};
+2

CRTP, , , .

template <typename Derived>
class BaseClass
{
   std::vector<float> &vector;

public:
   BaseClass(): vector(Derived::getVector()){};

};

class DerivedClass : public BaseClass<DerivedClass>
{
   public:

   static std::vector<float>& getVector()
   {
      static std::vector<float> v;
      return v;
   }

   DerivedClass() {};
};
+3

All Articles