Made sure that apply can never move or modify the tuple values; fixes #439 (#440)

This commit is contained in:
Dr. Patrick Urbanke (劉自成)
2025-05-28 08:12:50 +02:00
committed by GitHub
parent eb8ae352bc
commit 9e3f818761
3 changed files with 31 additions and 19 deletions
+2 -8
View File
@@ -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();
});
```
+1 -11
View File
@@ -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)), ...);
};
+28
View File
@@ -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