How do you implement this Python idiom in C++
benben
benhongh at yahoo.com.au
Mon Jul 31 06:54:33 EDT 2006
You are heading the wrong way...
There are a number of ways to implement this but the easiest I can think
of is to use RTTI.
To get around with counting sub-objects you can rely on virtual
inheritance, which only happens at the top of the inheritance tree.
Here is a simple demo:
#include <iostream>
#include <typeinfo>
#include <map>
class count
{
public:
typedef std::map<const std::type_info*, unsigned int> counts_t;
static counts_t counts;
const std::type_info* ti;
static unsigned int get_count(const std::type_info& c)
{return counts[&c];}
count(const std::type_info& c):ti(&c){++counts[ti];}
~count(){--counts[ti];}
};
count::counts_t count::counts;
class c1: virtual private count
{
public: c1(): count(typeid(c1)){}
};
class c2: public c1, virtual private count
{
public: c2(): count(typeid(c2)){}
};
int main()
{
c1 t1[3];
c2 t2[5];
std::cout << count::get_count(typeid(c1)) << "\n";
<< count::get_count(typeid(c2)) << "\n";
return 0;
}
More information about the Python-list
mailing list