count class instances for every derived class

前端 未结 7 2117
栀梦
栀梦 2021-02-19 09:09

is there any way to make all derived classes count their instances?How (write code in one of C++, C#, Java)?

Imagine I\'ve got access to the root class (e.g. object), an

7条回答
  •  故里飘歌
    2021-02-19 09:31

    In C++, you can do it with a template base class. Basically it is a mixin, so it does still require each class to co-operate by inheriting from the mixin:

    // warning: not thread-safe
    template 
    class instance_counter {
      public:
        static size_t InstancesCount() { return count(); }
        instance_counter() { count() += 1; }
        instance_counter(const instance_counter&) { count() += 1; }
        // rare case where we don't need to implement the copy assignment operator.
      protected:
        ~instance_counter() { count() -= 1; }
      private:
        static size_t &count {
            static size_t counter = 0;
            return counter;
        }
    };
    
    class my_class: public instance_counter {};
    

    Since each class using the template has a different base class, it has a different count function and hence a different copy of the static variable counter.

    The trick of inheriting from a template class that's instantiated using the derived class as a template parameter is called CRTP.

提交回复
热议问题