Re: templates, constructors, and references
Ulrich Eckhardt wrote:
Ross Boylan wrote:
I want to track creation and destruction of objects, so I created a
template that one uses like Count<Foo> to make a class that tracks the
necessary info in static variables. I want this to be a drop-in
replacement for Foo.
If it is to serve that role, it must have the same constructors as Foo.
So I tried
[ctor argument forwarding]
Ross, you could take a different approach and that is to use a 'mixin'
implemented with CRTP. Example:
CRTP = Curiously Recursive Template Pattern, right?
template<typename T>
class counted_type
{
counted_type( counted_type const&);
counted_type& operator=(counted_type const&);
protected:
counted_type() { ++s_instances; }
~counted_type() { --s_instances; }
public:
static size_t get_count() { return s_instances; }
private:
static size_t s_instances;
};
class Foo: public counted_type<Foo>
{...};
Uli
Thanks for a terrific suggestion. I think with one tweak this will work for
me. The problem is that my class Foo is already implemented (and for most
purposes I want it without the extra baggage). So I think I need:
class CountedFoo : public Foo, counted_type<Foo> {
// and then respecify needed c'tors for drop-in replacement, e.g.,
CountedFoo(const SomeClass& a, int b, OtherClass* pc) :
Foo(a, b, pc) {}
// I think I get counted_type<Foo> initialization without specifying
// it explicitly
}
I think that if my only references are through CountedFoo pointers I do not
need a virtual destructor, and that if I have some references through Foo
pointers and Foo lacks a virtual destructor this will not work.
Ross
--
loc
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]