diff --git a/include/rfl.hpp b/include/rfl.hpp index 825544c50..c7abcafc4 100644 --- a/include/rfl.hpp +++ b/include/rfl.hpp @@ -96,6 +96,7 @@ #include "rfl/to_view.hpp" #include "rfl/tuple_cat.hpp" #include "rfl/type_name_t.hpp" +#include "rfl/unwrap.hpp" #include "rfl/view_t.hpp" #include "rfl/visit.hpp" diff --git a/include/rfl/unwrap.hpp b/include/rfl/unwrap.hpp new file mode 100644 index 000000000..9a1dd4acf --- /dev/null +++ b/include/rfl/unwrap.hpp @@ -0,0 +1,47 @@ +#ifndef RFL_UNWRAP_HPP_ +#define RFL_UNWRAP_HPP_ + +#include +#include + +#include "internal/TransparentWrapper.hpp" +#include "internal/is_default_val_v.hpp" +#include "internal/is_deprecated.hpp" +#include "internal/is_description.hpp" +#include "internal/is_positional.hpp" +#include "internal/is_rename.hpp" +#include "internal/is_short.hpp" + +namespace rfl { + +namespace internal { + +template +constexpr bool is_metadata_wrapper_v = + is_default_val_v || is_description_v || is_deprecated_v || + is_rename_v || is_short_v || is_positional_v || + is_transparent_wrapper_v; + +} // namespace internal + +/// Recursively unwraps reflect-cpp metadata wrappers (DefaultVal, Description, +/// Deprecated, Rename, Short, Positional, and all transparent CLI wrappers) +/// and returns a reference to the underlying value. Does not unwrap +/// std::optional, pointers, or Validator. +template +constexpr decltype(auto) unwrap(T&& _val) noexcept { + using U = std::remove_cvref_t; + if constexpr (internal::is_metadata_wrapper_v) { + if constexpr (std::is_lvalue_reference_v) { + return unwrap(_val.value()); + } else { + return unwrap(std::move(_val.value())); + } + } else { + return std::forward(_val); + } +} + +} // namespace rfl + +#endif diff --git a/tests/cli/test_unwrap.cpp b/tests/cli/test_unwrap.cpp new file mode 100644 index 000000000..fd7a81cc7 --- /dev/null +++ b/tests/cli/test_unwrap.cpp @@ -0,0 +1,37 @@ +#include + +#include +#include +#include +#include + +namespace test_unwrap { + +struct Config { + rfl::Group<"COMMON OPTIONS", + rfl::Short<"v", rfl::Description<"Verbose", rfl::DefaultVal>>> + verbose = false; + rfl::Group<"OUTPUT OPTIONS", + rfl::Short<"o", rfl::Description<"Output", + std::optional>>> + output; + rfl::Hidden>> input = "in.osm"; +}; + +TEST(cli, test_unwrap_nested_wrappers) { + const std::vector args = {"-v", "-o", "out.osm"}; + const auto res = + rfl::cli::read(args); + ASSERT_TRUE(res) << res.error().what(); + EXPECT_TRUE(rfl::unwrap(res->verbose)); + ASSERT_TRUE(rfl::unwrap(res->output).has_value()); + EXPECT_EQ(*rfl::unwrap(res->output), "out.osm"); + EXPECT_EQ(rfl::unwrap(res->input), "in.osm"); + + // Mutable reference works too. + auto cfg = *res; + rfl::unwrap(cfg.verbose) = false; + EXPECT_FALSE(rfl::unwrap(cfg.verbose)); +} + +} // namespace test_unwrap