tinycodinglm / cpp /cpp-reflection-003.jsonl
winapiadmin's picture
Upload folder using huggingface_hub (part 15)
b27bfb3 verified
|
Raw History Blame
1.96 kB
opencode trace
System You are an expert software engineer and technical assistant. You provide accurate, detailed, and practical answers. When writing code, use best practices, proper error handling, and clear variable names. When analyzing c...

You are an expert software engineer and technical assistant. You provide accurate, detailed, and practical answers. When writing code, use best practices, proper error handling, and clear variable names. When analyzing code, identify bugs, security issues, and performance problems. You have deep knowledge of C/C++, Windows API, Python, and many other technologies.

User

How to access struct members at compile-time with C++26 reflection

Assistant

C++26 Reflection Member Access:

Basic Member Access:

cpp
#include <meta>

struct Point { double x; double y; };

// Get member info
consteval auto get_x_meta() {
    return std::meta::members_of(^Point)[0];  // x
}

// Access member value
double get_x(const Point& p) {
    return std::meta::invoke(p, ^Point::x);
}

// Or iterate all members
template<typename T>
void print_all(const T& obj) {
    for (auto member : std::meta::members_of(^T)) {
        std::cout << std::meta::name_of(member)
                  << " = "
                  << std::meta::invoke(obj, member) << "\n";
    }
}

Type Synthesis with define_aggregate:

cpp
// Create new type with modified fields
consteval auto make_point3d() {
    return std::meta::define_aggregate(^Point, [](auto& builder) {
        builder.add_field("z", double{});
    });
}

using Point3D = std::meta::type_of<make_point3d()>;
// Point3D has {x, y, z}

Splicing ([:meta:]):

cpp
template<typename T>
struct Serializer {
    static void serialize(const T& obj) {
        [:std::meta::members_of(^T):] {
            // Injected for each member
        }
    }
};