Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save safiire/0bf2dd21b209540a698c to your computer and use it in GitHub Desktop.
Save safiire/0bf2dd21b209540a698c to your computer and use it in GitHub Desktop.
Curiously Recurring Template Pattern
////
// Curiously Recurring Template Pattern
#include <stdio.h>
template <typename T>
struct Counter {
// Static class members variables
static int objects_created;
static int objects_alive;
Counter(){
++objects_created;
++objects_alive;
}
protected:
~Counter(){ // Don't let people delete via pointer
--objects_alive;
}
};
// Set the initial value, this will come not come into effect
// unless Counter's template is instantiated, and will instantiate
// a separate template class for each T.
template <typename T> int Counter<T>::objects_created(0);
template <typename T> int Counter<T>::objects_alive(0);
// X and Y are derived from a base class which takes themselves as
// a template argument to Counter, this will run the above static
// initializations, and run Counter<X>'s constructors, which are
// separate classes.
// When an X or Y is destructed, Counter<>'s destructor will run too.
class X : Counter<X> {};
class Y : Counter<Y> {};
int main(int argc, char **argv){
printf("Interesting Object Counter with Templates\n");
// Create some Xs on the stack.
X x1;
X x2;
X x3;
{
// Create some Ys inside an inner scope.
Y y1;
Y y2;
printf("X Objects Created %d\n", Counter<X>::objects_created);
printf("X Objects Alive %d\n", Counter<X>::objects_alive);
printf("Y Objects Created %d\n", Counter<Y>::objects_created);
printf("Y Objects Alive %d\n", Counter<Y>::objects_alive);
// The Ys are destroyed here.
}
printf("X Objects Created %d\n", Counter<X>::objects_created);
printf("X Objects Alive %d\n", Counter<X>::objects_alive);
printf("Y Objects Created %d\n", Counter<Y>::objects_created);
printf("Y Objects Alive %d\n", Counter<Y>::objects_alive);
/* Outputs
Interesting Object Counter with Templates
X Objects Created 3
X Objects Alive 3
Y Objects Created 2
Y Objects Alive 2
X Objects Created 3
X Objects Alive 3
Y Objects Created 2
Y Objects Alive 0
*/
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment