psionic12
psionic12

Reputation: 305

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?

P.S. 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.

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

Upvotes: 3

Views: 5222

Answers (2)

Andreas H.
Andreas H.

Reputation: 6095

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

To realize this without tricks (e.g. 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).

Upvotes: 4

janekb04
janekb04

Reputation: 4945

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.

Upvotes: 2

Related Questions