I wanted to check if there's an intuitive and easy way to access struct fields by name in modern C++. I am aware that similar questions have been asked and answered, and C++ reflection is a well investigated subject. I've came across libraries like:
But the common point in all these approaches is that, they only allow you to get the total number of fields within the struct or do a certain operation in for_each
manner for all the fields of the struct.
Yes, I can obviously check for the specific "name" of the field I'm looking for, by using the for_each
functionality provided by these libraries. But I just wanted to check if there is any other trivial/well-know library that already does this.
I would like to be able to deal with arbitrary number of nested structs, which is why I'm looking for something out of the box.
As Louis Go indicated, it would be great to have an accessor like:
auto field = namespace::getField<mystruct>("fieldname");
auto field = namespace::getField<mystruct>("fieldname");
? – Penneypennistruct
can have fields of different type so you would have to obtain aunion
,std::variant
orstd::any
. Which one do you want? – Cuttingstd::variant
with all the possible types within the struct specified would be OK – Loiseloiter