0

Suppose there is an object which contains some data members, like this:

class MyObject {
   int age;
   string name;
   bool is_cool;
   …

   get(string member_name);  // returns the value of member
}; 

and now there is a MyIterator object by which I could iterate over all the MyObject, and during which I want to get some of the data members of MyObject, like the pseudo code below:

get_members(vector<string> member_names, vector<*> &output) {
  MyIterator it;
  while (it.next_myobject()) {
    for (name in member_names) {
       output.push_back(it.get(name))
    }
  }
}

My problem is, I don’t know how I could implement this idea, but if I only get 1 data member, I know how to implement this by defining a template function, like this:

template <typename T>
get_member(string member_name, vector<T> &output) {
  MyIterator it;
  while (it.next_myobject()) {
    output.push_back(it.get<T>(member_name));
  }
}

Give me some help :-)

avocado
  • 2,615
  • 3
  • 24
  • 43

1 Answers1

1

You have to work out what static type you're going to store in the output vector, given you have multiple logical data types. boost::any (which uses RTTI so you can test for specific types later), and boost::variant (which is a discriminated union able to store any of a set list of types) are reasonable choices. If you don't want to use boost, you can at least refer to their documentation to understand the concepts, then look at implementing something minimal and similar, though I'd recommend avoiding that as you'll waste time writing/debugging it....

If your needs are really simple, you may be able to settle for string representations of all the values (i.e. std::vector<std::string>& output, use a std::istringstream to get a representation of an arbitrary type).

Tony Delroy
  • 102,968
  • 15
  • 177
  • 252