c++ - How to keep track of multiple object instances? -
i made base class object track instances of objects. want log in file so:
object name: number of instances here base class:
template <class t> class countedobj { public: countedobj() { // write name of derived class , counter log } countedobj(const countedobj& obj) { // write name of derived class , counter log } ~countedobj() { // write name of derived class , counter log } private: int counter; mylogger log; }; my problem want print name of class inherit countedobj, can't use typeid inside constructor.
is there alternative log object allocated , deallocated ?
you didn't specified how use countedobj. assume this:
class foo: public countedobj<foo> { }; if derive further foo, counter unable differentiate between foo, , derived classes, suppose want print "foo" name derived classes. if want differentiate between these classes, different solution needed (i'll delete answer if that's case).
(or maybe can derive again countedobj: class fooderived: public foo, public countedobj<fooderived> { };, way, fooderived counted both fooderived , foo)
so, can use typeid way:
template <typename t> class countedobj { public: countedobj() { counter++; printf("%s: %d\n", typeid(t).name(), counter); } private: static int counter; // static needed }; if don't output typeid().name(), can add static name-query function foo:
template <typename t> class countedobj { public: countedobj() { counter++; printf("%s: %d\n", t::name(), counter); } ... }; class foo: public countedobj<foo> { public: static const char *name() { return "foo"; } };
Comments
Post a Comment