FWIW, tested today at work that this works on a recent gcc. pretty poor
style, mem management and safety are disregarded, just a demo. but the core
of it is only about 20 lines of code.
you still have to add new shapes to that vector, but I assume if you have a
system that everything derives from a grandpa Object class, then it is
easier to do such a thing as language support. OTOH, at no point does one
have to spell out any class names except at the use site.
there is no way to call a member by its name in C++ though.
struct Shape { virtual string id() { return "shape"; } };
struct Circle : public Shape { string id() { return "circle"; }};
struct Triangle : public Shape { string id() { return "triangle"; }};
typedef mpl::vector shapes;
string demangle(char* name) {
int status;
char* dmgled = abi::__cxa_demangle(name,0,0,&status);
if(res) return res;
return name;
}
struct shape_select {
Shape*& shape;
string name;
shape_select(Shape*& s, string n) : shape(s),name(n) {}
template
void operator()(T&) {
if(name == demangle(typeid(T).name()))
shape = new T;
}
};
Shape* create_shape_by_name(string name) {
Shape* shape = 0;
shape_select worker(shape, name);
mpl::for_each(worker);
return shape;
}
int main() {
cout<id()<cout<id()<}