CPP26 静态反射初探
近日gcc已经把静态反射合并到...
近日gcc已经把静态反射合并到了主分支,
预览版也支持到了静态反射
预计就这两个月gcc16.1也要出了
话不多说,直接下载预览版体验:
https://gcc.gnu.org/pub/gcc/snapshots/LATEST-16/
直接make && make install编译安装
xmake写入(为了支持静态反射):
set_languages("cxx26")
add_cxxflags("-std=gnu++2c", {force = true})
add_cxxflags("-fpermissive")
add_cxxflags("-freflection")
使用最新静态反射提案的代码实现一个反射to_string!
#include <meta>
#include <print>
#include <string>
#include <vector>
namespace meta = std::meta;
namespace print_utility {
struct skip_t {};
constexpr inline static skip_t skip;
struct rename_t {
const char* name;
};
consteval rename_t rename(std::string_view name) {
return rename_t(std::define_static_string(name));
}
} // namespace print_utility
/// annotations_of => annotations_of_with_type
consteval std::optional<std::meta::info> get_annotation(std::meta::info entity,
std::meta::info type) {
auto annotations = meta::annotations_of_with_type(entity, type);
if (annotations.empty()) {
return {};
} else if (annotations.size() == 1) {
return annotations.front();
} else {
throw "too many annotations!";
}
}
consteval auto fields_of(std::meta::info type) {
return std::define_static_array(
meta::nonstatic_data_members_of(type, meta::access_context::unchecked()));
}
template <typename T>
auto to_string(const T& value) -> std::string {
constexpr auto type = meta::remove_cvref(^^T);
if constexpr (!meta::is_class_type(type)) {
return std::format("{}", value);
} else if constexpr (meta::is_same_type(type, ^^std::string)) {
return value;
} else {
std::string result;
result += meta::identifier_of(type);
result += " { ";
bool first = true;
template for (constexpr auto member : fields_of(type)) {
if constexpr (get_annotation(member, ^^print_utility::skip_t)){
continue;
}
if (!first) {
result += ", ";
}
first = false;
std::string_view field_name = meta::identifier_of(member);
constexpr auto rename = get_annotation(member, ^^print_utility::rename_t);
if constexpr (rename) {
constexpr auto annotation = *rename;
field_name = meta::extract<print_utility::rename_t>(annotation).name;
}
result += std::format("{}: {}", field_name, to_string(value.[:member:]));
}
result += " }";
return result;
}
}
struct Cat{
std::string name;
int age;
std::string owner;
};
int main(){
Cat c{.name="VC", .age=2, .owner="laull"};
std::println("{}", to_string(c));
}
输出:
Cat { name: VC, age: 2, owner: laull }
完美!