Unpacking std :: array

I tried to unpack std::arraythrough std::tie:

#include <tuple>
#include <array>

int main() {
    std::array<int, 3> arr = {1, 2, 3};
    int a, b, c;
    std::tie(a, b, c) = arr;
    return 0;
}

It works in the clang, but not compiled into ++ 5.4 g: no match for ‘operator=’. Compilation options -std=c++11.

  • Why does this work in clang but not g ++?
  • How to transfer unpacking std::array, how can I unpack a tuple?

Thanks for any help!

+4
source share
1 answer

I would create a special function to convert an array to a tuple. C ++ 14 code might look like this:

template <class T, std::size_t N, std::size_t... Is>
auto unpack_impl(std::array<T, N> &arr, index_sequence<Is...>) -> decltype(std::make_tuple(arr[Is]...)) {
    return std::make_tuple( arr[Is]... );
}

template <class T, std::size_t N>
auto unpack(std::array<T, N> &arr) -> decltype(unpack_impl(arr, make_index_sequence<N>{})) {
    return unpack_impl(arr, make_index_sequence<N>{});
}

And then use it like:

std::array<int, 3> arr = {{1, 2, 3}};
int a, b, c;
std::tie(a, b, c) = unpack(arr);

In C ++ 11 you will need to implement integer_sequenceit since it does not fail in the standard ...

Here you can find the complete C ++ 11 solution.

Edit:

, . make_tuple, const , :

template <class T, std::size_t N, std::size_t... Is>
auto unpack_impl(std::array<T, N> &arr, index_sequence<Is...>) -> decltype(std::tie( arr[Is]... )) {
    return std::tie( arr[Is]... );
}

Edit2:

VS

+1

Source: https://habr.com/ru/post/1662754/


All Articles