1

I'm trying to figure out what is the best approach here. Basically I have a system where I receive external requests in order to set/get values in my model. The problem is that my model consists on C++ classes, which can be nested, whereas the requests are simple (key, value) pairs.

For example:

struct Foo {
    void setX(int x);
    int getX() const;

    struct Boo {
        void setY(float y);
        float getY() const;
    }:
};

If I receive a request that says set(y, 21) for a given element e, then the actions I need to perform will be different depending on whether or not foo and boo already exist. Having to take care of the different possibilities for each property would end up in writing a lot of code.

Before reinventing the wheel, I was wondering if there is already a library or a well-known technique in C++ that allows mapping this flat actions into changes in C++ structures (which can be nested) in a generic way.

Thanks

user1192525
  • 657
  • 4
  • 20
  • I don't think its possible, what if both the inner and outer class had a member 'y'? – BWG Jan 09 '15 at 14:50
  • that's a separate problem... anyway, you could have two different keys (e.g. 'fooY' and 'booY') in order to identify each member in a unique way. – user1192525 Jan 09 '15 at 14:55
  • It sounds like you're looking for reflection. Unfortunately, reflection is intentionally minimal in C++. You might be able to pull something off using pointers to member functions, but I wouldn't want to maintain that. – Max Lybbert Jan 09 '15 at 14:59

1 Answers1

4

Boost has Property Maps for this purpose.

The most elementary interface it exposes is

get(map, key)
put(pmap, key, val)

For lvalue/readable maps you can also get indexer style access

pmap[key];
pmap[key] = newval; // if not const/readonly

You can a existing property map adaptors:

  • identity_property_map and typed_identity_property_map
  • function_property_map
  • iterator_property_map
  • shared_array_property_map
  • associative_property_map
  • const_associative_property_map
  • vector_property_map
  • ref_property_map
  • static_property_map
  • transform_value_property_map
  • compose_property_map

or write custom ones.

There is even a dynamic_property_map that looks like this, in practice:

put("age",properties,fred,new_age);
put("gpa",properties,fred,new_gpa);

Note that age and gpa could be stored anywhere (even requiring a web-request, perhaps) but the difference in access is abstracted away by the properymap interface that sits in between.


Samples from my answers:

Community
  • 1
  • 1
sehe
  • 374,641
  • 47
  • 450
  • 633