Boost.PFR Documentation

repository·develop·Indexed 23 days ago

https://github.com/boostorg/pfr

A header-only C++14 library providing lightweight reflection for aggregate structures. It enables index-based access via boost::pfr::get, field counting with boost::pfr::tuple_size, and serialization through boost::pfr::io without the use of macros or boilerplate code.

Tokens
696
Snippets
3
Records
5
Agent score
31%

What's inside Boost.PFR

  1. What is Boost.PFR and how does it work?

    develop

    Boost.PFR is a C++14 library that provides basic reflection capabilities for aggregate structures. It allows developers to:

    • Access structure elements by index (boost::pfr::get<N>).
    • Retrieve the number of fields in a type (boost::pfr::tuple_size).
    • Serialize structures to a string format (boost::pfr::io).

    It achieves this without the need for macros or manual boilerplate, making it highly compatible with existing user-defined aggregate types. It mimics the interface of std::tuple for custom structs.

  2. Install Boost.PFR

    develop
    Boost.PFR is a header-only C++14 library. It does not depend on other Boost libraries. To use it in your project, you can simply copy the contents of the include folder from the repository into your project's include path.
  3. Access structure elements by index with boost::pfr::get

    develop

    You can access individual fields of an aggregate structure by their index using boost::pfr::get<N>(instance). This works for any aggregate type without requiring macros or boilerplate code.

    #include "boost/pfr.hpp"
    #include <string>
    
    struct some_person {
      std::string name;
      unsigned birth_year;
    };
    
    some_person val{"Edgar Allan Poe", 1809};
    
    // Accessing elements by index
    auto name = boost::pfr::get<0>(val);
    auto year = boost::pfr::get<1>(val);
  4. Print aggregate structures with boost::pfr::io

    develop

    The boost::pfr::io(instance) function allows you to easily serialize an aggregate structure into a string-like format (e.g., for use with std::cout or file streams) without defining custom operator<< overloads for every struct.

    #include <iostream>
    #include "boost/pfr.hpp"
    
    struct my_struct {
        int i;
        char c;
        double d;
    };
    
    int main() {
        my_struct s{100, 'H', 3.141593};
        // Outputs: {100, H, 3.14159}
        std::cout << boost::pfr::io(s) << "\n";
    }
  5. Get the number of fields in a struct with boost::pfr::tuple_size

    develop

    To determine how many fields are in an aggregate structure, use boost::pfr::tuple_size<T>::value. This provides std::tuple-like reflection capabilities for user-defined types.

    #include "boost/pfr.hpp"
    
    struct my_struct {
        int i;
        char c;
        double d;
    };
    
    // Returns the number of fields (3)
    std::size_t size = boost::pfr::tuple_size<my_struct>::value;