Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11 std::tuple to std::array conversion causes variadic template crash

The following function, toArray, might one day convert a C++11 std::tuple into a C++11 std::array:

#include <tuple>
#include <array>

template <typename T, typename ...U>
std::array<T,sizeof...(U)>
toArray(std::tuple<U...>) {
  return std::array<T,sizeof...(U)>();
}

If I try to call toArray with the following code, under G++ 4.8 I can compile successfully. Compiling with Clang++ 3.2, however, crashes the Clang front-end. Is my code valid C++?

int main(int argc, char *argv[])
{
  auto tup = std::make_tuple(1,2,3,4,5,6,7,8);
  toArray<int>(tup);
  return 0;
}
like image 691
user2023370 Avatar asked Feb 22 '26 23:02

user2023370


1 Answers

It looks valid to me, and the finished version works fine with G++:

#include <redi/index_tuple.h>
template <typename T, typename... U, unsigned... N>
  std::array<T, sizeof...(U)>
  toArray2(std::tuple<U...>& t, redi::index_tuple<N...>) {
    return std::array<T, sizeof...(U)>{{ std::get<N>(t)... }};
  }

template <typename T, typename ...U>
  std::array<T, sizeof...(U)>
  toArray(std::tuple<U...> t) {
    return toArray2<T>(t, redi::to_index_tuple<U...>{});
  }

int main()
{
  auto tup = std::make_tuple(1,2,3,4,5,6,7,8);
  return toArray<int>(tup)[3] - 4;
}
like image 89
Jonathan Wakely Avatar answered Feb 25 '26 15:02

Jonathan Wakely



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!