#include //-------------------------------------------------------------------------------------------------------------------------------------- template struct CRTPcount { private: static uint32_t mCreated; static uint32_t mCurrent; protected: CRTPcount() { ++mCreated; ++mCurrent; } CRTPcount( const CRTPcount& ) { ++mCreated; ++mCurrent; } virtual ~CRTPcount() { --mCurrent; } public: static void usage_stats() { std::cout << "Class '" << typeid( T ).name() << "' | " << mCreated << " copies created | " << mCurrent << " copies currently alive" << std::endl; } }; //Remembering to instantiate the static member variable template uint32_t CRTPcount::mCreated( 0 ); template uint32_t CRTPcount::mCurrent( 0 ); //-------------------------------------------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------------------------------------------- class DerivedClassA : public CRTPcount< DerivedClassA > {}; class DerivedClassB : public CRTPcount< DerivedClassB > {}; // Can be used for an arbitrary number of classes of arbitrary nature //-------------------------------------------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------------------------------------------- int main() { // -------------------- // Test default values DerivedClassA::usage_stats(); // -------------------- //Test default constructor DerivedClassA lA; DerivedClassA::usage_stats(); // -------------------- // Test copy constructor DerivedClassA lA2( lA ) ; DerivedClassA::usage_stats(); // -------------------- // Test destructor for( int i=0 ; i!=10 ; ++i ) DerivedClassB lB; //Scoped within the for-loop so they are created and immediately destroyed DerivedClassB::usage_stats(); // -------------------- return 0; } //--------------------------------------------------------------------------------------------------------------------------------------