简体   繁体   中英

Iterate members of struct in C++20

I remembered that C++20 got features to iterate over members in a struct,I read a blog about it with example codes, but I can't find it anymore.

For example:

struct Foo {
  std::string a;
  std::string b;
  std::string c;
}; 


struct Bar {
  std::string e;
  std::string f;
};

template <typename T>
void PrintMember (T& t) {
  // what to do to iterate members in C++ 20?
}

The code of the template may not look like that, since C++20 got concepts. Any idea how to write codes to iterate members in Foo and Bar ?

PS I remembered that it use concepts to do the trick, but maybe I'm wrong or the blog is wrong (that's why I can't find it anymore), an answer of "No you can't, even in C++20" is welcomed.

PPS One thing I didn't clarify, I don't need the field name, but I need to iterate for all fields, including inherited fields.

(Here I assume you would like to get the field name as well)

To realize this without tricks (eg additional tools or manual additions of meta information) you need the C++ reflection capability.

Even though it is available as a technical specification , this is not (yet) part of C++ (with C++20 being the latest standard to-date).

You can use the Boost PFR library . To print members of a struct you can simply use the built-in boost::pfr::io utility: ( godbolt )

template <typename T>
void PrintMember (const T& t) {
    std::cout << boost::pfr::io(t);
}

To be more general, you can use boost::pfr::for_each_field : ( godbolt )

template <typename T>
void PrintMember (const T& t) {
    boost::pfr::for_each_field(t, [](auto&& x){
        std::cout << x << ' ';
    });
}

Both solutions work in C++17.

Regarding printing member field names. I'm afraid it's not possible currently without explicitly specifying them. If you're fine with that, you can try using a C++ reflection library until reflection is integrated into the standard .

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