解压std :: array [英] Unpacking a std::array

查看:80
本文介绍了解压std :: array的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过 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;
}

此方法在clang中有效,但无法在g ++ 5.4中编译: operator = 没有匹配项。编译选项为 -std = c ++ 11

This works in clang, but fails to compile in g++ 5.4: no match for ‘operator=’. Compile options are -std=c++11.


  1. 为什么这样做

  2. 如何使用clang而不是g ++?

  3. 如何像一个人可能要拆开一个元组那样,方便地解包一个 std :: array ? li>
  1. Why does this work in clang but not g++?
  2. How can I portably unpack a std::array, like one might unpack a tuple?

谢谢您的帮助!

推荐答案

我将创建专用功能以将数组转换为元组。 C ++ 14代码可能如下所示:

I would create dedicated function to transform array to tuple. C++14 code could look as follows:

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

然后使用它:

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

在c ++ 11中,您将需要实现 integer_sequence ,因为它不是标准中的开箱即用...

In c++11 you would need however to implement integer_sequence as it does not come out of the box in the standard...

此处,您可以找到完整的c ++ 11解决方案。

Here you can find complete c++11 solution.

编辑:

如果数组包含一些更复杂的对象,则可能要避免不必要的复制。为此,您可以使用const引用的元组代替 make_tuple ,或者如果constness不打扰您,则可以简单地将数组元素捆绑起来:

If an array contains some more complex objects you might want to avoid unnecessary copy. To do that instead of make_tuple you may use tuple of const references or if the constness doesn't bother you you could simple tie array elements up:

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上编译

这篇关于解压std :: array的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆