How do you implement this Python idiom in C++

Rob Williscroft rtw at freenet.co.uk
Thu Jul 27 14:04:05 EDT 2006


 wrote in news:1154015441.807624.35160 at i42g2000cwa.googlegroups.com in 
comp.lang.python:

> #include <iostream>
> using namespace std;
> 
> // A base class that provides counting
> template<class T> class Counted {
>   static int count;

> };
> 
> template<class T> int Counted<T>::count = 0;
> 
> // Curious class definitions
> class CountedClass : public Counted<CountedClass> {};
> class CountedClass2 : public Counted<CountedClass2> {};
> 
> It apparently works but in fact it doesn't:
> If you derive from such a class, you get the count of the parent class,

You are mistaken about how it should work in the first place. 
It may well be that it doesn't do what you wan't it to.

To translate the python idom into C++ you need to replace
derivation with the CRTP (*) code the author supplied.

*) CRTP = Curiosly Recuring Template Pattern

> 
> not of the derived class.
> class CountedClass3 : public CountedClass {};

Don't use the above always use:

class CountedClass3 : public Counted< CountedClass3 > 
{
};

Note that the "classmethod emulation" stops here, if you need 
it to continue you will need to keep using the CRTP:

template < typename T = void >
class CountedClass : public Counted< CountedClass< T > > 
{
};

Create instances:

CountedClass<> cc; /* T = void */

Derive (keeping the "classmethod emulation") using the CRTP:

template < typename T = void > /* So we can "Derive" again */
class CountedClass2 : public CountedClass< CountedClass2< void > >
{
};

Note that the trick works by always making the instantition of
Counted< T > you are deriving from unique, CountedClass<> has
a base class Counted< CountedClass< void > > and CountedClass2<>
has (ultimatly) a base class Counted< CountedClass2< void > >.

Ofcouse the next problem is that CRTP-derivation above isn't real
derivation, this idom translation clearly has a breaking point.

If this is more than idle curiosity I strongly suggest you post 
a version of the python code you need to translate to C++.

Rob.
-- 
http://www.victim-prime.dsl.pipex.com/



More information about the Python-list mailing list