[英]C++ transform std::pair<std::pair<std::pair<A, B>, C>, D> to std::tuple<A, B, C, D>
I have such kind of code:我有这样的代码:
const auto temp = std::make_pair(std::make_pair(std::make_pair('Q', 1.2),
std::string("POWER")), 1);
std::cout << std::format("({}, {}, {}, {})\n", temp.first.first.first,
temp.first.first.second, temp.first.second, temp.second);
that obviously prints:这显然打印:
(Q, 1.2, POWER, 1)
I want to make it more readable and intuitive by converting "pair of pair and smth" to std::tuple
:我想通过将“pair and smth”转换为
std::tuple
使其更具可读性和直观性:
const auto temp = std::make_pair(std::make_pair(std::make_pair('Q', 1.2),
std::string("POWER")), 1);
const auto tuple = PairsToTuple(temp);
std::cout << std::format("({}, {}, {}, {})\n", std::get<0>(tuple),
std::get<1>(tuple), std::get<2>(tuple), std::get<3>(tuple));
How can I do that?我怎样才能做到这一点?
You can recursively std::tuple_cat
您可以递归地
std::tuple_cat
template<typename First, typename Second>
auto flatten(std::pair<First, Second> pair) {
return std::tuple_cat(flatten(pair.first), flatten(pair.second));
}
template<typename... Types>
auto flatten(std::tuple<Types...> tup) {
return std::apply([](auto... args) { return std::tuple_cat(flatten(args)...);}, tup);
}
template<typename T>
auto flatten(T t) {
return std::tuple{ t };
}
If you have C++20, we can generalise this to anything tuple-like with a concept :如果您有 C++20,我们可以将其推广到任何类似元组的概念:
template<typename T>
auto flatten(T&& t) {
if constexpr (tuple<std::remove_cvref_t<T>>) {
return [&]<std::size_t... Is>(std::index_sequence<Is...>) {
return std::tuple_cat(flatten(get<Is>(std::forward<T>(t)))...);
}(std::make_index_sequence<std::tuple_size_v<std::remove_cvref_t<T>>>{});
} else {
return std::tuple{ std::forward<T>(t) };
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.