Modern way to access struct fields by name in C++

Viewed 1860

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");
1 Answers

You can access class members by name using the member access operator. Example:

struct foo {
    int bar;
} instance;

instance.bar = 42; // access by name

If you mean to access a member based on a string variable rather than by compile time identifier, then no. C++ still as of C++20 does not have reflection features necessary to achieve this.

Quite often when programmers want this, what they actually need is an associative container such as std::map.

Related