Skip to content

Reflection in C++26 #7

Description

@nomhoi

Implementing a repository using reflection in C++26. AI generated:

#include <iostream>
#include <print>
#include <experimental/meta>
#include <string>
#include <vector>

using namespace std;

// Интерфейс репозитория
template <typename T>
class Repository {
public:
    void save(const T& entity) {
        constexpr auto type_refl = ^^T;
        constexpr auto ctx = meta::access_context::current();
        constexpr auto members = define_static_array(nonstatic_data_members_of(type_refl, ctx));

        string columns = "";
        string values = "";

        // Автоматически строим SQL-запрос через отражение
        template for (constexpr auto m : members) {
            if (!columns.empty()) { 
                columns += ", "; 
                values += ", "; 
            }
            
            columns += display_string_of(m);
            
            // Используем format вместо to_string для универсальности
            using T2 = typename [: type_of(m) :];
            if constexpr (std::convertible_to<T2, std::string_view>) {
                values += std::format("'{}'", entity.[:m:]);
            } else {
                values += std::format("{}", entity.[:m:]);
            }
        }


        println("SQL: INSERT INTO {} ({}) VALUES ({});", 
                display_string_of(type_refl), columns, values);
    }

    // Пример заглушки для поиска
    void find_all() {
        println("SQL: SELECT * FROM {};", display_string_of(^^T));
    }
};

// Сущности (POCO)
struct User {
    int id;
    string name;
};

struct Product {
    int id;
    string sku;
    int price;
};

int main() {
    Repository<User> userRepo;
    userRepo.save({1, "Alice"});

    Repository<Product> productRepo;
    productRepo.save({101, "KB-99", 500});

    productRepo.find_all();
}

https://godbolt.org/z/P7PKT84qG

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions