Search code examples
c++boostreflectionc++17

boost::pfr with customized member


I'm trying to use boost::pfr for basic reflection, and it fails to compile when one of the member is customized type, like a class or struct, why is this? What's the way to fix it? I'm using C++17.

// this works:
struct S1 {
    int n;
    std::string name;
};
S1 o1{1, "foobar"};
std::cout << boost::pfr::io(o1) << '\n';

// but this does not work:
struct S2 {
    int m;
    S1 s1; // <===== this fields fails to compile
};
S2 o2;
std::cout << boost::pfr::io(o2) << '\n';

Solution

  • You need to provide operator<< for S1, as boost::pfr::io relies on it existing:

    std::ostream& operator<<(std::ostream& os, const S1& x)
    {
        return os << boost::pfr::io_fields(x);
    }
    

    live example on godbolt.org