Boost logo

Boost :

From: Antony Polukhin (antoshkka_at_[hidden])
Date: 2020-10-07 15:11:34


ср, 7 окт. 2020 г. в 15:48, Andrzej Krzemienski <akrzemi1_at_[hidden]>:
> Interesting. I do not understand enough about the implementation to be making definite statements, but based on my superficial knowledge I expect that it should be possible to reimplement a "flat" reflection on top of "precise" one.
> 1. First you call structure_to_tuple() and you get std::tuple<T1&, T2&, ..., Tn&>
> 2. For every Tn that is an aggregate type you apply structure_to_tuple() recursively.
> 3. Then you potentially get a tuple of nested tuples and you need to flatten it.

Yes, that's doable. But is that really a popular feature?

Flat representation was useful, because there was no precise
representation in the early versions of the library. That was the only
way to do things.

Back to your example:

struct Person {
  std::string firstName;
  std::string lastName;
  int age;
};

struct Employee : Person {
  double salary;
};

struct Prisoner : Person {
  int cellNumber;
};

Probably composition would work better than inheritance for your needs?

struct Person {
  std::string firstName;
  std::string lastName;
  int age;
};

struct Employee {
  Person person;
  double salary;
};

struct Prisoner {
  Person person;
  int cellNumber;
};

With composition you get more flexibility:

std::ostream& operator<<(std::ostream& os, const Person& p) {
    os << "person: ";
    pfr::write(os, p);
    return os;
}

std::ostream& operator<<(std::ostream& os, const Prisoner& p) {
    using pfr::ops;
    return os << p;
}

// Outputs: {person: {"Harley ", "Quinn", 21}, 100500}
std::cout << Prinsoner{{"Harley ", "Quinn", 21}, 100500};

-- 
Best regards,
Antony Polukhin

Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk