1

What I want to do is randomly select members of a structure. I would create a an instance of the structure then it would got through a 'path' of it's members and arrive at the very last member. I am going to use this as a random item generator. so it will create something like this:

item new_item;

Then it would randomly select which members it has.

new_item.item_class.part1.part2.end

Keeping in mind that the parts of the item will be randomly selected. I have no idea how to implement this and I have searched everywhere for a starting point.

b28c92e5ff1
  • 489
  • 1
  • 4
  • 17
  • 3
    If you haven't done so already, please read this thread: http://stackoverflow.com/questions/41453/how-can-i-add-reflection-to-a-c-application – kfmfe04 Feb 18 '12 at 01:03

2 Answers2

1

That is not possible in C++, not unless you manually code a description of your structures and the functions to follow them.

In other words, you will only get this functionality if you manually implement it yourself. The C++ runtime won't keep the needed information around.

Edit: there are libraries that can aid in creating code for reflection mechanisms in C++ through templates and macros. Try googling around for "reflection in C++".

salezica
  • 74,081
  • 25
  • 105
  • 166
1

That doesn't make sense. C++ is a statically typed language, so you have to determine at compile time which types you want to work with. You cannot pick a "random type" in C++, and consequently you cannot refer to a "random class member".

The only sensible thing that you can do is pick a random element from a homogeneous container like a vector or an array (essentially by picking a random index).

Note that a collection of base class pointers is indeed a homogeneous collection that can be used to handle a heterogeneous set of objects, but they must all derive from the same type. Visitors (using dynamic casts) can be used to process the actual concrete instances. Perhaps this may be a useful approach, so let me write an example:

struct Object { virtual ~Object() { } };

struct Foo : Object { /* ... */ };
struct Bar : Object { /* ... */ };

std::vector<std::unique_ptr<Object>> v;

// populate v, e.g. "v.emplace_back(new Bar);"

for (auto & p : v)
{
    if (Foo * q = dynamic_cast<Foo*>(p.get())) { /* use q */ }

    else if /* further cast attempts */
}
Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084