Skip to content

Commit

Permalink
✨ Add forward_as_tuple
Browse files Browse the repository at this point in the history
  • Loading branch information
elbeno committed Sep 25, 2023
1 parent 0540d81 commit f2a8e35
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 3 deletions.
12 changes: 9 additions & 3 deletions docs/tuple.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -28,17 +28,23 @@ them, but if not, it's quicker to compile just an alias and a variable template.

=== Constructing a tuple

A `tuple` can be constructed either with CTAD, or with `make_tuple`.
A `tuple` can be constructed either with CTAD, or with `make_tuple`, or with
`forward_as_tuple`.

[source,cpp]
----
auto t = stdx::tuple{1, 2}; // tuple<int, int>
auto t = stdx::make_tuple(1, 2); // the same
auto t = stdx::tuple{1, 2}; // tuple<int, int>
auto t = stdx::make_tuple(1, 2); // the same
auto t = stdx::forward_as_tuple(1, 2); // tuple<int&&, int&&>
----

`make_tuple` decays its arguments, just like `std::make_tuple`. However,
`std::make_tuple` also does `std::reference_wrapper`-unwrapping, which
`stdx::make_tuple` does not.

`forward_as_tuple` creates a tuple of forwarded references, like
`std::forward_as_tuple`.

=== Accessing tuple elements

The ordinary way to access tuple elements is to use `get`, as with a `std::tuple`:
Expand Down
3 changes: 3 additions & 0 deletions include/stdx/tuple.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -423,6 +423,9 @@ constexpr auto apply_indices(T &&t) {
}(std::make_index_sequence<tuple_size_v<tuple_t>>{});
}

template <typename... Ts> auto forward_as_tuple(Ts &&...ts) {
return stdx::tuple<Ts &&...>{std::forward<Ts>(ts)...};
}
} // namespace v1
} // namespace stdx

Expand Down
8 changes: 8 additions & 0 deletions test/tuple.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -399,3 +399,11 @@ TEST_CASE("tuple type-based concat", "[tuple]") {
static_assert(std::is_same_v<typename detail::concat<T, U>::type,
stdx::tuple<int, float>>);
}

TEST_CASE("forward_as_tuple", "[tuple]") {
auto const x = 42;
auto y = 42;
auto t = stdx::forward_as_tuple(x, y, 42);
static_assert(
std::is_same_v<decltype(t), stdx::tuple<int const &, int &, int &&>>);
}

0 comments on commit f2a8e35

Please sign in to comment.