[C++-sig] fat class decoration
Mike Rovner
mike at nospam.com
Fri Oct 24 00:34:59 CEST 2003
Hi,
I solicit a criticism and possible better solutions to the following
problem.
I have a nonmodifyable C++ class
class T
{
public:
Color* getColor(const char* name);
void setColor(const char* name, const Color* value);
Line* getLine(const char* name);
void setLine(const char* name, const Line* value);
//and so on
};
with a bunch of classes Color, Line, etc.
I want pretend in Python interface that T has bunch of attributes 'color',
'line', etc.
that behave like mappings each, i.e. I want to be able to say in Python:
t=T()
t.color["a"]=Color(...)
print t.line["b"]
For that purpose I created helper classes and generator functions
class TColorHelper
{
T& _t;
public:
TColorHelper(T& t) : _t(t) {}
Color* get(const char* name) { return _t.getColor(name); }
void set(const char* name, const Color* value)
{_t.setColor(name,value);}
};
TColorHelper color(T& t) { return TColorHelper(t); }
class TLineHelper {...}; line(){...} //and so on for each property
wrap them:
class_<TColorHelper>("TColorHelper", no_init)
.def("__getitem__", &TColorHelper::get, return_internal_ref<>())
.def("__setitem__", &TColorHelper::set)
;
//...
class_<T>("T")
.add_property("color", color)
.add_property("line", line)
;
which works fairly well.
So what do think about it?
Maybe you have had similar problem and solved it differently.
I appreciate your comments.
Thanks,
Mike
More information about the Cplusplus-sig
mailing list