Reputation: 13
Let's assume we have a template class ptr. The constructor function of ptr class can take values of int, double, another handmade structure etc since it is a template class.
I want to see exactly how many times these constructors and destructors are called and also the type of the data that it has been called for. Is this possible to see?
Right now I have a static int value in the template class and 2 constructors (1 default constructor) and 1 destructors in which I increase/decrease the value of the static int value.
template<class T>
class ptr
{
private:
T* data;
public:
ptr();
ptr(T* data);
~ptr();
static int number;
};
template<class T>
int ptr<T>::number = 0;
How can I see for which types these constructors and destructor are called? All I see now the value of the static int, not for which type it is called.
Upvotes: 0
Views: 336
Reputation: 238361
I want to see exactly how many times these constructors and destructors are called...
Well that's easy, you store that number in ptr<T>::number
, so yes, it's possible to see. For example, to see how many times ptr<Foo>
has been instantiated, use ptr<Foo>::number
.
and also the type of the data that it has been called for
It's not possible to get that kind of information from your template. That's essentially asking: what are all instances ptr
whose constructor has been called?
What you could do, is define a global map of std::type_index
to int
. Since that map wouldn't be limited to one template, it could keep track of calls to costructors of any instance of ptr
.
It might be worth noting that you can only get an implementation defined, mangled, name of the type using std::type_index
, so if you want a prettier typename, then you'll need some way to map the std::type_index
to what you want. If you limit the possible types to select few, you could keep your own map of std::type_index
to std::string
and use that for printing, or you could use platform specific demangling.
EDIT: Storing the type - count map in a non-template parent class (in the similar way as Elemental's answer for total count) would probably be more appropriate than storing it globally.
Upvotes: 1
Reputation: 7521
If you do wish to count all instances (independent of type) you might try to give them a common non-templated super class:
class uniptr {
protected:
static int number;
}
template<class T>
class ptr: public uniptr
{
private:
T* data;
public:
ptr();
ptr(T* data);
~ptr();
};
This seems to do what you want with some reasonable encapsulation. If it's not immediately clear this works because there is only one class uniptr declared (and therefore only one static int) even though there might be multiple versions of ptr used (likeptr<int>
and ptr<String>
).
Upvotes: 1