How to Use C++26 Reflections Properly and Make the Best Use of Them?

I’m exploring the upcoming C++26 reflections feature and I’m excited about its potential to simplify many tasks that involve introspection and metaprogramming. However, I’m not entirely sure how to use reflections properly and how to leverage them for various use cases effectively.

Could someone provide examples of how to use C++26 reflections correctly? Specifically, I’m interested in:

  1. Basic usage of reflections to introspect type information.
  2. How to iterate over members of a struct or class.
  3. Practical use cases like serialization, debugging, and automated testing.

Any code examples and explanations would be highly appreciated!

Examples of Structs:

struct Person {
    std::string name;
    int age;
    double height;
};

struct Address {
    std::string street;
    int number;
};

Desired Outputs:

  1. Print type information of Person and Address.
  2. Iterate over members of these structs and print their names and types.
  3. Serialize an instance of Person to a string (e.g., JSON format).

1

Some of the API, particularly around recovering strings that represent names, is still in flux. The latest published revision contains an example of how to build a universal formatter, although we’re thinking about introducing an API that is spelled identifier_of(mem) instead.

So the intended implementation right now (assuming we get expansion statements) would look like this:

struct universal_formatter {
  constexpr auto parse(auto& ctx) { return ctx.begin(); }

  template <typename T>
  auto format(T const& t, auto& ctx) const {
    auto out = std::format_to(ctx.out(), "{}{{", identifier_of(^T));

    auto delim = [first=true]() mutable {
      if (!first) {
        *out++ = ',';
        *out++ = ' ';
      }
      first = false;
    };

    template for (constexpr auto base : bases_of(^T)) {
      delim();
      out = std::format_to(out, "{}", (typename [: type_of(base) :] const&)(t));
    }

    template for (constexpr auto mem : nonstatic_data_members_of(^T)) {
      delim();
      out = std::format_to(out, ".{}=", identifier_of(mem));

      // this whole dance because we don't have :?
      ctx.advance_to(out);
      std::formatter<typename [:type_of(mem):]> f;
      std::format_parse_context pctx("");
      (void)f.parse(pctx);
      if constexpr (requires { f.set_debug_format(); }) {
        f.set_debug_format();
      }
      out = f.format(t.[:mem:], ctx);
    }

    *out++ = '}';
    return out;
  }
};

With which, you could:

struct Person {
    std::string name;
    int age;
    double height;
};

// explicit opt-in, but note that you don't 
// have to do anything other than this
template <> struct std::formatter<Person> : universal_formatter { };

int main() {
    // prints: Person{.name="Caeleb Dressel", .age=27, .height=1.9}
    std::println("{}", Person{.name="Caeleb Dressel", .age=27, .height=1.90});
}

Since we don’t have expansion statements, there’s an awkward workaround. But it is still doable: demo.

Iterate Over Members

#include <iostream>
#include <experimental/reflection>

namespace reflect = std::experimental::reflection;

struct Address {
    std::string street;
    int number;
};

template <typename T>
void iterateMembers() {
    constexpr auto typeInfo = reflect::reflect<T>();

    for (auto member : typeInfo.members()) {
        std::cout << "Member name: " << member.name() << 'n';
        std::cout << "Member type: " << member.type().name() << 'n';
    }
}

int main() {
    iterateMembers<Address>();
    return 0;
}

2

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật