我想实现一个通用的
具体来说,实现如下(为简洁起见,省略了处理空元组的部分):
在第一种情况下,我们使用
tuple_map
函数,它接受一个函数对象和一个std::tuple
,将该函数应用于元组的每个元素,并返回结果的std::tuple
。实现非常简单,但问题是:这个函数应该返回什么类型?我的实现使用了std::make_tuple
。然而,这里建议使用std::forward_as_tuple
。具体来说,实现如下(为简洁起见,省略了处理空元组的部分):
#include <cstddef>
#include <tuple>
#include <type_traits>
#include <utility>
template<class Fn, class Tuple, std::size_t... indices>
constexpr auto tuple_map_v(Fn fn, Tuple&& tuple, std::index_sequence<indices...>)
{
return std::make_tuple(fn(std::get<indices>(std::forward<Tuple>(tuple)))...);
// ^^^
}
template<class Fn, class Tuple, std::size_t... indices>
constexpr auto tuple_map_r(Fn fn, Tuple&& tuple, std::index_sequence<indices...>)
{
return std::forward_as_tuple(fn(std::get<indices>(std::forward<Tuple>(tuple)))...);
// ^^^
}
template<class Tuple, class Fn>
constexpr auto tuple_map_v(Fn fn, Tuple&& tuple)
{
return tuple_map_v(fn, std::forward<Tuple>(tuple),
std::make_index_sequence<std::tuple_size_v<std::remove_reference_t<Tuple>>>{});
}
template<class Tuple, class Fn>
constexpr auto tuple_map_r(Fn fn, Tuple&& tuple)
{
return tuple_map_r(fn, std::forward<Tuple>(tuple),
std::make_index_sequence<std::tuple_size_v<std::remove_reference_t<Tuple>>>{});
}
在第一种情况下,我们使用
std::make_tuple
,它会衰减每个参数的类型(对于值使用_v
),而在第二种情况下,我们使用std::forward_as_tuple
,它会保留引用(对于引用使用_r
)。这两种情况都有其优缺点。
Dangling references.
auto copy = [](auto x) { return x; }; auto const_id = [](const auto& x) -> decltype(auto) { return x; }; auto r1 = tuple_map_v(copy, std::make_tuple(1)); // OK, type of r1 is std::tuple<int> auto r2 = tuple_map_r(copy, std::make_tuple(1)); // UB, type of r2 is std::tuple<int&&> std::tuple<int> r3 = tuple_map_r(copy, std::make_tuple(1)); // Still UB std::tuple<int> r4 = tuple_map_r(const_id, std::make_tuple(1)); // OK now
Tuple of references.
auto id = [](auto& x) -> decltype(auto) { return x; }; int a = 0, b = 0; auto r1 = tuple_map_v(id, std::forward_as_tuple(a, b)); // Type of r1 is std::tuple<int, int> ++std::get<0>(r1); // Increments a copy, a is still zero auto r2 = tuple_map_r(id, std::forward_as_tuple(a, b)); // Type of r2 is std::tuple<int&, int&> ++std::get<0>(r2); // OK, now a = 1
Move-only types.
NonCopyable nc; auto r1 = tuple_map_v(id, std::forward_as_tuple(nc)); // Does not compile without a copy constructor auto r2 = tuple_map_r(id, std::forward_as_tuple(nc)); // OK, type of r2 is std::tuple<NonCopyable&>
References with
std::make_tuple
.auto id_ref = [](auto& x) { return std::reference_wrapper(x); }; NonCopyable nc; auto r1 = tuple_map_v(id_ref, std::forward_as_tuple(nc)); // OK now, type of r1 is std::tuple<NonCopyable&> auto r2 = tuple_map_v(id_ref, std::forward_as_tuple(a, b)); // OK, type of r2 is std::tuple<int&, int&>
可能我理解错误或者漏掉了一些重要的东西。
看起来make_tuple
是正确的选择:它不会产生悬空引用,同时仍然可以强制推导出引用类型。您将如何实现tuple_map
(以及与之相关的陷阱)?
auto fn = [](auto const& x) { return std::cref(x); }; auto a = fn(2);
,我们将得到一个悬空引用,而没有任何元组参与。我的结论是使用forward_as_tuple
,知道(小)注意事项。 - Rerito