7

I would like to have a struct (or something similar) in C++, that will allow access to its members dynamically. It should have a generic getter and setters that receive the member name as a string, and return some sort of variant type (e.g. boost::variant).

I was thinking it could be implemented using boost::fusion::map, by adding a string representing the name of each member, and building an STL map between strings and getter or setter functions. I don't want to reinvent the wheel, so I was hoping something similar already existed.

What do you think? Would my idea work? Do you know other ways to accomplish my goal?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
haggai_e
  • 4,689
  • 1
  • 24
  • 37
  • 2
    I wonder why you want this? Even in languages that directly support it, reflection is a hack used to get around bad code, or cheap code for lazy programmers. – John Dibling Dec 02 '10 at 13:51
  • You're defeating the type-safety C++ gives you. What on Earth can justify exchanging such a simple, strong tool for correctness with a messy hack for achieving uncertainty? – wilhelmtell Dec 02 '10 at 14:18
  • @wilhelmtell: I'm trying to find the right balance. I'm reading values from a very uncertain source, and they need to be parsed and handled in a generic way. Only for a small part of them I know (and want to know) the right type. – haggai_e Dec 02 '10 at 14:49
  • 2
    @Dibling: I always thought that lazy programmers where the best programmers ... – haggai_e Dec 02 '10 at 14:52
  • so about using a standard container of various types rather than a struct? – wilhelmtell Dec 02 '10 at 15:51
  • I want this to make a serializable base class, so I can just declare the field names and types, and from that info generate serialize and unserialize functions. At the moment, I'm repeating the field names in both places, which is gonna be bad in the future. – matiu Jul 10 '11 at 13:13

3 Answers3

7

fusion is an approach, but why not store your "fields" in a std::map keyed by a std::string, where the payload is the boost::variant...

i.e.

struct generic
{
std::map<std::string, boost::variant<foo, bar, bob, int, double> > _impl;
};

and then you can just lookup the key in your getter/setter...

heck, wrap the variant in an optional and you could have optional fields!

a more complex example:

class foo
{
public:
  typedef boost::variant<int, double, float, string> f_t;
  typedef boost::optional<f_t&> return_value;
  typedef map<string, return_value> ref_map_t;

  foo() : f1(int()), f2(double()), f3(float()), f4(string()), f5(int()) 
  {
    // save the references..
    _refs["f1"] = return_value(f1);
    _refs["f2"] = return_value(f2);
    _refs["f3"] = return_value(f3);
    _refs["f4"] = return_value(f4);
    _refs["f5"] = return_value(f5);
  }

  int getf1() const { return boost::get<int>(f1); }
  double getf2() const { return boost::get<double>(f2); }
  float getf3() const { return boost::get<float>(f3); }
  string const& getf4() const { return boost::get<string>(f4); }
  int getf5() const { return boost::get<int>(f5); }

  // and setters..
  void setf1(int v) { f1 = v; }
  void setf2(double v) { f2 = v; }
  void setf3(float v) { f3 = v; }
  void setf4(std::string const& v) { f4 = v; }
  void setf5(int v) { f5 = v; }

  // key based
  return_value get(string const& key)
  {
    ref_map_t::iterator it = _refs.find(key);
    if (it != _refs.end())
      return it->second;
    return return_value();
  }

  template <typename VT>
  void set(string const& key, VT const& v)
  {
    ref_map_t::iterator it = _refs.find(key);
    if (it != _refs.end())
      *(it->second) = v;
  }

private:
  f_t f1;
  f_t f2;
  f_t f3;
  f_t f4;
  f_t f5;

  ref_map_t _refs;
};

int main(void)
{
  foo fancy;
  fancy.setf1(1);
  cout << "f1: " << fancy.getf1() << endl;

  fancy.set("f1", 10);
  cout << "f1: " << fancy.getf1() << endl;

  return 0;
}
Nim
  • 33,299
  • 2
  • 62
  • 101
  • This would work, but I prefer having strict type checking, and faster runtime access in the cases when I do know the field name at compile time. – haggai_e Dec 02 '10 at 13:01
  • okay, in that case store in the map references to the real fields (which are of type variant - example above)... – Nim Dec 02 '10 at 13:27
  • The problem here is that there are 5 places where I need to add a new field. This seems like a lot of boilerplate for adding what consists only of a compile-time name, a string, and the type. Maybe I could modify your solution by having the fields public (and with their non-variant type), and storing in the map some kind of wrappers that converted each to and from a variant. – haggai_e Dec 02 '10 at 14:18
  • I eventually wrote something more complex: instead of holding a map with variants, I created a map that had string keys, and getter and setter functions for values. The getters and setters then accessed a boost::fusion::map object to get the actual values. But this solution was more complicated then necessary... – haggai_e Jun 22 '11 at 12:56
1

You are asking for Reflection in C++ which I think is not available. You will have to come up with something of your own.

Aamir
  • 14,882
  • 6
  • 45
  • 69
  • RTTI is available in C++, you're thinking of *reflection*... :) – Nim Dec 02 '10 at 12:55
  • Yes, reflection in C++ would make it much simpler. I'll settle for a solution that requires minimal new lines of code for adding a new field. – haggai_e Dec 02 '10 at 12:57
1

What I did for this was a boost::cons-like type-list that contains my members and some kind of description. I then build this mapping by successively adding my members to a "meta-info" data structure by "chained" function calls. The whole thing looks very similar to defining a class in boost.python. If you actually use boost::cons, it should also work as a sequence in boost.fusion, so you can iterate nicely over your data. Maybe you can use a boost.fusion map instead to get log(n) access times at run-time, but it seems their size is limited until variadic templates are available.

ltjax
  • 15,837
  • 3
  • 39
  • 62