17

Suppose we have a struct in C++:

struct foobar
{
      int age; 
      bool hot;
      String name
};

Is there a way, programatically, to query the above struct to extract its instance members? For example:

String[] members = magicClass.getInstanceMembers(foobar);

Members would have ["age", "hot", "name"] as it's values.

Possible? The reason why I ask is because I have structs that change over time (variables added/removed). I want to be able to create auto-generating Lua files with this saved data.

Thanks

Alan Haggai Alavi
  • 72,802
  • 19
  • 102
  • 127

3 Answers3

14

No, standard C++ doesn't support that type of reflection. There are some "hacky" ways using macros to create a type-traits-esque template that will use SFINAE to statically determine whether or not a particular class has a certain data member or member function, but nothing that will actually enumerate every member of a class.

In fact, C++ was designed with a certain philosophy in mind that would make it difficult, if not counter-productive, to support the type of runtime reflection we see in higher-level languages like C#/Java. See Why does C++ not have reflection? for a thorough discussion on this issue.

Community
  • 1
  • 1
Charles Salvia
  • 52,325
  • 13
  • 128
  • 140
  • Shoot. Another reason why Java is king for non OS/low level stuff –  Nov 05 '10 at 21:06
  • 11
    @Carlo del Mundo: Actually most people see this as a plus. Though reflection is really useful for building developers tools. In real code it is not that useful and often leads to horrible to maintain code (of course there are always exceptions). – Martin York Nov 05 '10 at 21:10
  • 2
    @Martin, true, but I would like to see better support for *compile-time* reflection, which could help enhance template library designs. Regardless, I think the best use-case of reflection is for implementing generic serialization functions. – Charles Salvia Nov 05 '10 at 21:18
  • 2
    For example, imagine a meta-function that used recursive template instantiation to iterate over all data members in a class. This would allow the compiler to generically generate serialization functions for any class, without any of the runtime overhead necessitated by Java-style reflection. – Charles Salvia Nov 05 '10 at 21:21
1

I think what you're looking for is called Reflection. This is not easy to do in C / C++: http://www.garret.ru/cppreflection/docs/reflect.html http://en.wikipedia.org/wiki/Reflection_(computer_science)

Marcin
  • 12,245
  • 9
  • 42
  • 49
1

If you really, really want to write "c++" code with reflection you can look at what ROOT does with cint and the makecint code-generator. But this probably isn't what you really want to do...

dmckee --- ex-moderator kitten
  • 98,632
  • 24
  • 142
  • 234