C/C++ Possible to get a "list" of instance members by querying a class?
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 chang开发者_开发问答e over time (variables added/removed). I want to be able to create auto-generating Lua files with this saved data.
Thanks
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.
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)
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...
精彩评论