Home > Net >  C transform std::pair<std::pair<std::pair<A, B>, C>, D> to std::tuple<A, B, C
C transform std::pair<std::pair<std::pair<A, B>, C>, D> to std::tuple<A, B, C

Time:08-11

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:

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?

CodePudding user response:

You can recursively 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 tup;
}

template<typename T>
auto flatten(T t) {
    return std::tuple{ t };
}

See it on coliru

  • Related