boost - Accessing members in a C++ struct both dynamically and statically -


i have struct (or similar) in c++, allow access members dynamically. should have generic getter , setters receive member name string, , return sort of variant type (e.g. boost::variant).

i thinking implemented using boost::fusion::map, adding string representing name of each member, , building stl map between strings , getter or setter functions. don't want reinvent wheel, hoping similar existed.

what think? idea work? know other ways accomplish goal?

thanks, haggai

fusion approach, why not store "fields" in std::map keyed std::string, payload boost::variant...

i.e.

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

and can lookup key in getter/setter...

heck, wrap variant in optional , 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 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); }    // , 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 = _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 = _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; } 

Comments

Popular posts from this blog

asp.net - repeatedly call AddImageUrl(url) to assemble pdf document -

java - Android recognize cell phone with keyboard or not? -

iphone - How would you achieve a LED Scrolling effect? -