Boost logo

Boost Users :

Subject: [Boost-users] Get fields from struct
From: Matthijs Möhlmann (matthijs_at_[hidden])
Date: 2012-01-13 06:34:45


Hello all,

I'm currently busy to get things like this working:

struct person {
  std::string name;
  int age;
};

int main(int argc, char **argv) {

  person p;
  p.name = "Matthijs"
  p.age = 1234;

  std::string key = "name";

  // Now try to fetch the value based on the key string.
  std::cout << p.{key} << std::endl; // does not compile

  return 0;
}

Of course above doesn't work for obvious reasons.

The closest I get is:

struct person {
        std::string name;
        int age;
};

namespace keys {
        struct name;
        struct age;
}

BOOST_FUSION_ADAPT_ASSOC_STRUCT(
        person,
        (std::string, name, keys::name)
        (int, age, keys::age)
);

int main(int argc, char **argv) {

        person x;
        x.name = "Matthijs";
        x.age = 1234;

        std::cout << "Name: " << boost::fusion::at_key<keys::name>(x) << std::endl;
        std::cout << "Age: " << boost::fusion::at_key<keys::age>(x) << std::endl;

        return 0;
}

Now my question, is there maybe another way to achieve this?

Regards,

Matthijs Möhlmann
Cacholong


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net