0

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?

frogatto
  • 28,539
  • 11
  • 83
  • 129
Tobs
  • 27
  • 3
  • Which version of c++ are we using here? The solution will be different after c++11 and again after c++17 – Richard Hodges Sep 03 '17 at 11:58
  • Template classes cannot reside in shared libraries (dll/so files), their source code is required in compile-time, not runtime. Maybe they are in the `.h` interface file between the library and your code. – frogatto Sep 03 '17 at 12:04
  • Im currently using MS Visual Studio Community 17 (Platform Toolset: v141), I guess that's C++17. – Tobs Sep 03 '17 at 13:51
  • I was using VS15 or maybe 17 at the time. – Tobs Mar 05 '20 at 06:51

0 Answers0