Skip to content

Commit ca9e67a

Browse files
authored
Merge pull request #270 from elbeno/query-env-with-default
✨ Add `query` to look up values in environment
2 parents abf8702 + fb07ebf commit ca9e67a

File tree

2 files changed

+34
-1
lines changed

2 files changed

+34
-1
lines changed

include/stdx/env.hpp

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,20 @@ using append_env_t = boost::mp11::mp_unique_if<
9393

9494
template <_env::autowrap... Args>
9595
using make_env_t = extend_env_t<env<>, Args...>;
96+
97+
template <envlike Env, typename Q> constexpr auto query(Q q) -> decltype(auto) {
98+
return q(Env{});
99+
}
100+
101+
template <envlike Env, typename Q, typename Default>
102+
constexpr auto query(Q q, [[maybe_unused]] Default &&d) -> decltype(auto) {
103+
if constexpr (requires { q(Env{}); }) {
104+
return q(Env{});
105+
} else {
106+
return std::forward<Default>(d);
107+
}
108+
}
109+
96110
} // namespace v1
97111
} // namespace stdx
98112

test/env.cpp

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,10 +18,29 @@ namespace {
1818
} custom;
1919
} // namespace
2020

21-
TEST_CASE("lookup query with default", "[env]") {
21+
TEST_CASE("lookup query with internal default", "[env]") {
2222
STATIC_REQUIRE(custom(stdx::env<>{}) == 42);
2323
}
2424

25+
TEST_CASE("lookup query with default (free function)", "[env]") {
26+
STATIC_REQUIRE(stdx::query<stdx::env<>>(custom) == 42);
27+
}
28+
29+
namespace {
30+
[[maybe_unused]] constexpr inline struct custom_no_default_t {
31+
template <typename T>
32+
[[nodiscard]] CONSTEVAL auto operator()(T &&t) const
33+
noexcept(noexcept(std::forward<T>(t).query(std::declval<custom_t>())))
34+
-> decltype(std::forward<T>(t).query(*this)) {
35+
return std::forward<T>(t).query(*this);
36+
}
37+
} custom_no_default;
38+
} // namespace
39+
40+
TEST_CASE("lookup query with external default", "[env]") {
41+
STATIC_REQUIRE(stdx::query<stdx::env<>>(custom_no_default, 42) == 42);
42+
}
43+
2544
TEST_CASE("make an environment", "[env]") {
2645
using E = stdx::make_env_t<custom, 17>;
2746
STATIC_REQUIRE(custom(E{}) == 17);

0 commit comments

Comments
 (0)