mirror of
https://codeberg.org/DawnMagnet/reflect-cpp
synced 2026-11-29 22:36:19 +08:00
This commit is contained in:
+2
-8
@@ -103,15 +103,9 @@ auto person = rfl::Field<"first_name", std::string>("Bart") *
|
||||
rfl::Field<"last_name", std::string>("Simpson");
|
||||
|
||||
person.apply([](const auto& f) {
|
||||
auto field_name = f.name();
|
||||
const auto& value = *f.value();
|
||||
});
|
||||
|
||||
person.apply([]<typename Field>(Field& f) {
|
||||
// The field name can also be obtained as a compile-time constant.
|
||||
constexpr auto field_name = Field::name();
|
||||
using field_pointer_type = typename Field::Type;
|
||||
field_pointer_type* value = f.value();
|
||||
auto field_name = f.name();
|
||||
const auto& value = f.value();
|
||||
});
|
||||
```
|
||||
|
||||
|
||||
@@ -185,17 +185,7 @@ class NamedTuple {
|
||||
|
||||
/// Invokes a callable object once for each field in order.
|
||||
template <typename F>
|
||||
void apply(F&& _f) {
|
||||
const auto apply_to_field =
|
||||
[&_f]<typename... AFields>(AFields&&... fields) {
|
||||
((_f(std::forward<AFields>(fields))), ...);
|
||||
};
|
||||
rfl::apply(apply_to_field, fields());
|
||||
}
|
||||
|
||||
/// Invokes a callable object once for each field in order.
|
||||
template <typename F>
|
||||
void apply(F&& _f) const {
|
||||
void apply(F&& _f) const& {
|
||||
const auto apply_to_field = [&_f](const auto&... fields) {
|
||||
((_f(fields)), ...);
|
||||
};
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
#include <cassert>
|
||||
#include <iostream>
|
||||
#include <rfl.hpp>
|
||||
#include <rfl/json.hpp>
|
||||
#include <string>
|
||||
#include <type_traits>
|
||||
#include <vector>
|
||||
|
||||
#include "write_and_read.hpp"
|
||||
|
||||
namespace test_apply_on_named_tuple {
|
||||
|
||||
TEST(json, test_apply_on_named_tuple) {
|
||||
auto person = rfl::Field<"first_name", std::string>("Bart") *
|
||||
rfl::Field<"last_name", std::string>("Simpson");
|
||||
|
||||
const auto print = [](const auto& f) {
|
||||
const auto& name = f.name();
|
||||
const auto& value = f.value();
|
||||
std::cout << name << ", " << value << std::endl;
|
||||
};
|
||||
|
||||
person.apply(print);
|
||||
|
||||
EXPECT_EQ(rfl::json::write(person),
|
||||
R"({"first_name":"Bart","last_name":"Simpson"})");
|
||||
}
|
||||
} // namespace test_apply_on_named_tuple
|
||||
Reference in New Issue
Block a user