C++ 将 std::p air<std::p air<std::p air<A, B>, C>, D> 转换为 std::tuple<A, B, C, D&



我有这样的代码:

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);

明显打印:

(Q, 1.2, POWER, 1)

我想通过转换";成对和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));

我该怎么做?

您可以递归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 };
}

在coliru 上查看

如果你有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) };
}
}

在coliru 上查看

相关内容

最新更新