C/C++ Possible to get a “list” of instance members by querying a class?

自作多情 提交于 2019-12-23 06:56:46

问题


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


回答1:


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.




回答2:


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)




回答3:


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...



来源:https://stackoverflow.com/questions/4110037/c-c-possible-to-get-a-list-of-instance-members-by-querying-a-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!