-
Notifications
You must be signed in to change notification settings - Fork 8
Open
Description
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();
}
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
No labels