Boost C++ Libraries Home Libraries People FAQ More

PrevUpHomeNext

PFR as a C++20 module

[Caution] Caution

C++20 PFR module support is on early stage, targets, flags and behavior may change in the future

If using modern CMake define CMake option -DPFR_USE_MODULES=1 to build a C++20 module and make the pfr::pfr CMake target provide it. After that an explicit usage of C++20 module pfr is allowed:

#include <iostream>
#include <iomanip>
#include <string>

import pfr;

struct some_person {
    std::string name;
    unsigned birth_year;
};

int main() {
    some_person val{"Edgar Allan Poe", 1809};

    std::cout << pfr::get<0>(val)                // No macro!
        << " was born in " << pfr::get<1>(val);  // Works with any aggregate!

    std::cout << '\n' << pfr::io(val);           // Outputs: {"Edgar Allan Poe", 1809}
    std::cout << "\n." << pfr::get_name<0, some_person>()
        << '=' << val.name << '\n';                     // Outputs: .name=Edgar Allan Poe
}

The pfr::pfr CMake target gives an ability to mix includes and imports of the PFR library in different translation units. Moreover, if PFR_USE_MODULES macro is defined then all the pfr/... includes implicitly do import pfr; to give all the benifits of modules without changing the existing code.

[Note] Note

For better compile times make sure that import std; is available when building the pfr module (in CMake logs there should be a 'Using import std;' message).

If not using CMake, then the module could be build manually from the modules/pfr.cppm file.

For manual module build the following commands can be used for clang compiler:

cd pfr/module
clang++ -I ../include -std=c++20 --precompile -x c++-module pfr.cppm

After that, the module could be used in the following way:

clang++ -std=c++20 -fmodule-file=pfr.pcm pfr.pcm usage_sample.cpp

PrevUpHomeNext