简体   繁体   中英

Get list of available data member from a POD struct in C++

the question can sound a bit unusual. Let's take a POD struct:

struct MyStruct
{
   int myInt;
   double myDouble;
   AnotherPOD* myPointer;
};

The compiler knows the list of available data members. Do you know any way to get list of data member name (and type) either at compile time (better) or at run time?

I have a huge amount of POD structs and I would like to automate the creation of operator<<.

I know I could create a parser for the header files, create some files and compile those. However, I am sure the compiler has already had this information and I would like to exploit it.

Any ideas?

Thanks

BOOST_FUSION_ADAPT_STRUCT introduces compile-time reflection (which is awesome).

It is up to you to map this to run-time reflection of course, and it won't be too easy, but it is possible in this direction, while it would not be in the reverse :)

I don't know of any way to do what you want directly, but you might want to take a look at clang, which is a compiler front-end implementation that you can make use of to do other things:

http://clang.llvm.org

I guess you'd then be able to traverse the abstract syntax tree it creates and get at the information you're after.

Well, standard C++ compilers can't do that, they lack reflection capabilities.

Sounds like a task for a code generator. So either use a toolkit to extract these informations from the headers or generate both headers and serialization functions from another source. Just make sure you do not repeat yourself .

I am afraid but C++ doesn't support reflection. You can use Boost.TypeTraits to achieve a restricted form of reflection at compile time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM