Get the flattened tuple type from an arbitrarily nested tuple type

Viewed 158

I would like to have a type trait flatten_tuple_t which can create a flattened tuple type from an arbitrarily nested one. The following code snippet illustrates what is expected from flatten_tuple_t.

template <typename T>
struct flatten_tuple {
  using type = T;
};
// The real implementation goes here
// ...
// ...
template <typename T>
using flatten_tuple_t = typename flatten_tuple<T>::type;

// Dummy classes
struct C1 {};
struct C2 {};
struct C3 {};
struct C4 {};
struct C5 {};
struct C6 {};

int main(int argc, char* argv[]) {
  static_assert(
      std::is_same_v<flatten_tuple_t<std::tuple<C6, C5, std::tuple<C4, std::tuple<C3>, C2>, C1>>,
                     std::tuple<C6, C5, C4, C3, C2, C1>>);

  static_assert(std::is_same_v<flatten_tuple_t<std::tuple<std::tuple<std::tuple<C3>, C2>, C1>>,
                               std::tuple<C3, C2, C1>>);
}


1 Answers

You can make std::tuple_cat() do the heavy lifting for you.

The only tricky part is having to wrap the base types in a std::tuple<>. But since we need to use partial specialization to extract the types, we can just use the base template for that instead of leaving it undefined.

template <typename T>
struct flatten_tuple {
    using type = std::tuple<T>;
};

template <typename T>
using flatten_tuple_t = typename flatten_tuple<T>::type;

template <typename... Ts>
struct flatten_tuple<std::tuple<Ts...>> {
    using type = decltype(
        std::tuple_cat(std::declval<flatten_tuple_t<Ts>>()...)
    );
};

If using type = T; in the base case is an absolute must, then renaming the struct flatten_tuple_helper and delegating to it is fairly trivial.

Related