How can I add reflection to a C++ application?

2018-12-31 02:33发布

I'd like to be able to introspect a C++ class for its name, contents (i.e. members and their types) etc. I'm talking native C++ here, not managed C++, which has reflection. I realise C++ supplies some limited information using RTTI. Which additional libraries (or other techniques) could supply this information?

30条回答
美炸的是我
2楼-- · 2018-12-31 03:08

I think you might find interesting the article "Using Templates for Reflection in C++" by Dominic Filion. It is in section 1.4 of Game Programming Gems 5. Unfortunately I dont have my copy with me, but look for it because I think it explains what you are asking for.

查看更多
宁负流年不负卿
3楼-- · 2018-12-31 03:08

Check out Classdesc http://classdesc.sf.net. It provides reflection in the form of class "descriptors", works with any standard C++ compiler (yes it is known to work with Visual Studio as well as GCC), and does not require source code annotation (although some pragmas exist to handle tricky situations). It has been in development for more than a decade, and used in a number of industrial scale projects.

查看更多
唯独是你
4楼-- · 2018-12-31 03:09

The two reflection-like solutions I know of from my C++ days are:

1) Use RTTI, which will provide a bootstrap for you to build your reflection-like behaviour, if you are able to get all your classes to derive from an 'object' base class. That class could provide some methods like GetMethod, GetBaseClass etc. As for how those methods work you will need to manually add some macros to decorate your types, which behind the scenes create metadata in the type to provide answers to GetMethods etc.

2) Another option, if you have access to the compiler objects is to use the DIA SDK. If I remember correctly this lets you open pdbs, which should contain metadata for your C++ types. It might be enough to do what you need. This page shows how you can get all base types of a class for example.

Both these solution are a bit ugly though! There is nothing like a bit of C++ to make you appreciate the luxuries of C#.

Good Luck.

查看更多
像晚风撩人
5楼-- · 2018-12-31 03:09

There is another new library for reflection in C++, called RTTR (Run Time Type Reflection, see also github).

The interface is similar to reflection in C# and it works without any RTTI.

查看更多
看淡一切
6楼-- · 2018-12-31 03:10

Try to look at this project http://www.garret.ru/cppreflection/docs/reflect.html is added reflections to C++. It added meta data to the classes that you can then use.

查看更多
无色无味的生活
7楼-- · 2018-12-31 03:10

lack of built in reflection in C++ is the single reason why modern C++ is not used for web development (and lacks ORM and other frameworks)

You can try http://www.extreme.indiana.edu/reflcpp/

查看更多
登录 后发表回答