如何在不直接提供大小的情况下使用初始化列表创建 std::array

How to create std::array with initialization list without providing size directly(如何在不直接提供大小的情况下使用初始化列表创建 std::array)

本文介绍了如何在不直接提供大小的情况下使用初始化列表创建 std::array的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎样才能使 a3 编译?

How can I make a3 compile?

int main()
{
    int a1[] = { 1, 2, 3 };
    std::array<int, 3> a2 = { 1, 2, 3 };
    std::array<int> a3 = { 1, 2, 3 };
}

在使用初始化列表时,对数组的大小进行硬编码是非常不方便且脆弱的,尤其是长列表.有什么解决办法吗?我希望如此,否则我会很失望,因为我讨厌 C 数组,而 std::array 应该是它们的替代品.

It's very inconvenient, and brittle, to hard-code the size of the array when using an initialization list, especially long ones. Is there any work around? I hope so otherwise I'm disappointed because I hate C arrays and std::array is supposed to be their replacement.

推荐答案

目前没有办法不滚动自己的make_array,有一个建议N3824: make_array 具有以下范围:

There is currently no way to do this without rolling your own make_array, there is a proposal for this N3824: make_array which has the following scope:

LWG 851 旨在提供一种替代语法

LWG 851 intended to provide a replacement syntax to

array<T, N> a = { E1, E2, ... };

,所以如下

auto a = make_array(42u, 3.14);

格式正确(内部应用了额外的 static_casts),因为

is well-formed (with additional static_casts applied inside) because

array<double, 2> = { 42u, 3.14 };

格式正确.

本文拟提供一套std::array创建接口从元组的角度和数组的角度来看都是全面的角度来看,所以收窄自然是被禁止的.查看更多详情由设计决策中的这个方向驱动.

This paper intends to provide a set of std::array creation interfaces which are comprehensive from both tuple’s point of view and array’s point of view, so narrowing is just naturally banned. See more details driven by this direction in Design Decisions.

它还包括一个示例实现,它相当长,所以在这里复制是不切实际的,但康拉德鲁道夫有一个简化版本这里 与上面的示例实现一致:

It also includes a sample implementation, which is rather long so copying here is impractical but Konrad Rudolph has a simplified version here which is consistent with the sample implementation above:

template <typename... T>
constexpr auto make_array(T&&... values) ->
    std::array<
       typename std::decay<
           typename std::common_type<T...>::type>::type,
       sizeof...(T)> {
    return std::array<
        typename std::decay<
            typename std::common_type<T...>::type>::type,
        sizeof...(T)>{std::forward<T>(values)...};
}

这篇关于如何在不直接提供大小的情况下使用初始化列表创建 std::array的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何在不直接提供大小的情况下使用初始化列表创建 std::array

基础教程推荐