I am stuck with the following problem: I want to determine at run-time how many instances of a specific object family (i.e. objects with the same base class) exist. My current approach is to use a template class with a static int value as counter. Each time a new instances of the object family is created I increase the count.
Here is some code:
StaticTypeCounter.h
template<class T>
class MY_API StaticTypeCounter
{
static int s_count;
public:
static inline int Increment() { return s_count++; }
static inline int Get() { return s_count; }
};
StaticTypeCounter.cpp
class base1;
class base2;
StaticTypeCounter<base1>::s_count = 0;
StaticTypeCounter<base2>::s_count = 0;
template class StaticTypeCounter<base1>;
template class StaticTypeCounter<base2>;
Some dummy classes:
class A : public base1
{
public:
static const int STATIC_TYPE_ID;
};
class B : public base1
{
public:
static const int STATIC_TYPE_ID;
};
class C : public base2
{
public:
static const int STATIC_TYPE_ID;
};
const int A::STATIC_TYPE_ID = StaticTypeCounter<base1>::Increment(); // 0
const int B::STATIC_TYPE_ID = StaticTypeCounter<base1>::Increment(); // 1
const int C::STATIC_TYPE_ID = StaticTypeCounter<base2>::Increment(); // 0
This code works quite well, BUT you have to explicitly instantiate the StaticTypeCounter
template for each family. Additionally you may have notices StaticTypeCounter
resides in a shared library.
My question: Is there a way NOT to depend on the explicit template instantiation?