pure C的我没兴趣搞了。
AI给的modern c++方式的:
#include <iostream>
#include <string>
#include <sstream>
#include <tuple>
// ---- 反射机制 ----
template<typename T>
struct Field {
std::string_view name;
T const* ptr;
};
#define REFLECTABLE(...) \
static auto reflect_fields(const auto& self) { \
return std::make_tuple(__VA_ARGS__); \
}
#define FIELD(member) Field{#member, &self.member}
// ---- 用户结构体 ----
struct Employee {
int id;
double salary;
std::string name;
REFLECTABLE(
FIELD(id),
FIELD(salary),
FIELD(name)
)
};
// ---- SQL 生成 ----
template<typename T>
std::string SQL_insert(std::string_view table, const T& obj)
{
auto fields = T::reflect_fields(obj);
std::ostringstream sql;
sql << "INSERT INTO " << table << " (";
bool first = true;
std::apply([&](auto&&... f) {
((sql << (first ? (first = false, "") : ",") << f.name), ...);
}, fields);
sql << ") VALUES (";
first = true;
std::apply([&](auto&&... f) {
((sql << (first ? (first = false, "") : ",") << ":" << f.name), ...);
}, fields);
sql << ")";
return sql.str();
}
// ---- 调试输出 ----
template<typename T>
void SQL_bind_and_debug(const T& obj)
{
auto fields = T::reflect_fields(obj);
std::apply([&](auto&&... f) {
(([&] {
using FieldType = std::decay_t<decltype(*f.ptr)>;
if constexpr (std::is_same_v<FieldType, int>)
std::cout << "Bind int :" << f.name << " = " << *f.ptr << "\n";
else if constexpr (std::is_same_v<FieldType, double>)
std::cout << "Bind double :" << f.name << " = " << *f.ptr << "\n";
else if constexpr (std::is_same_v<FieldType, std::string>)
std::cout << "Bind string :" << f.name << " = '" << *f.ptr << "'\n";
}()), ...);
}, fields);
}
// ---- 测试 ----
int main()
{
Employee e{1001, 55000.5, "Alice"};
auto sql = SQL_insert("employee", e);
std::cout << sql << "\n";
SQL_bind_and_debug(e);
}
【 在 ylh1969 的大作中提到: 】
: 补充一点,数据库操作,可以使用离散变量或struct。
: 但是离散变量,我没办法写出通用函数,所以必然要通过一个技术:
: Struct Relational Mapping ,相当于JAVA的ORM。结构体与数据库表结构的对应。
: ...................
--
FROM 111.199.144.*