Using C ++ template programming to extract field types of arbitrary structure

If I define a structure with arbitrary data types, for example:

struct custom_type {
    int a;
    float b;
    char c; 
    float *d; // etc...
};

Is there a common template using template programming (C ++) to extract the field types of this structure and map them to some special code handler at compile time?

In some context: I am creating an api that allows clients to define their own custom user types and still allows integration with the base system that I use to manage and analyze these types, manage automated memory and other housekeeping.

A wrapping pattern or other mechanism will allow this integration without a base system, knowing anything about a header file that defines a custom type. From the client’s point of view, the code accesses the structure in the usual way, but the template allows using the general processing of each field in the structure.

Thank.

+4
source share
2 answers

, ++. . , , ​​ (, clang); , .

+1

, , reflection. ++, , (). .

"boost/pfr" ( ) . README:

// requires: C++14
#include <iostream>
#include <string>
#include "boost/pfr/precise.hpp"

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

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

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

README ( ),

  • T constexpr aggregate initializable

CppCon 2016 "++ 14 Reflections Without Macros, Markup External Tooling.." .

0

All Articles