count class instances for every derived class

前端 未结 7 2065
栀梦
栀梦 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:46

    I would use a template. This is in C++, by the way.

    template class object {
    private:
        static int count;
    public:
        object() { count++; }
        object(const object&) { count++; }
        ~object() { count--; }
        static int GetCount() { return count; }
    };
    template int object::count = 0;
    

    RTTI solution:

    class object {
        static std::map counts;
    public:
        object() { counts[typeid(*this).name()]++; }
        object(const object&) { counts[typeid(*this).name()]++; }
        ~object() { counts[typeid(*this).name()]--; }
        template int GetObjectsOfType() {
            return counts[typeid(T).name()];
        }
        int GetObjectsOfType(std::string type) {
            return counts[type];
        }
    };
    std::map object::counts;
    

    RTTI is less invasive and allows run-time selection of the type to be queried, but the template has far less overhead and you can use it to count every derived class individually, whereas RTTI can only count the most derived classes individually.

提交回复
热议问题