How do you implement this Python idiom in C++

Pierre Barbier de Reuille p.barbierdereuille at free.fr
Thu Jul 27 12:15:50 EDT 2006


alainpoint at yahoo.fr wrote:
> Hello,
> 
> I have the need to write the equivalent of Python class methods in C++.
> 
> Chuck Allison proposes the following
> (http://www.artima.com/cppsource/simple.html):
> #include <iostream>
> using namespace std;
> 
> // A base class that provides counting
> template<class T> class Counted {
>   static int count;
> public:
>   Counted() { ++count; }
>   Counted(const Counted<T>&) { ++count; }
>   ~Counted() { --count; }
>   static int getCount() { return 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,
> 
> not of the derived class.
> class CountedClass3 : public CountedClass {};
> 
> int main() {
>   CountedClass a;
>   cout << CountedClass::getCount() << endl;    // 1
>   CountedClass b;
>   cout << CountedClass::getCount() << endl;    // 2
>   CountedClass3 c;
>   cout << CountedClass3::getCount() << endl;   // 3 and should be 1
>   cout << CountedClass::getCount() << endl;    // 3 and should be 2
> 
> }
> 
> I am no C++ expert but i guess there might be some in the Python and
> C++ newsgroups. 
> 
> Alain
> 

Why don't you post the Python code you want to "translate" ? Here, I
just don't know what you want to achieve !!

Pierre



More information about the Python-list mailing list