使用初始化列表初始化数组?

11

这有可能吗?

#include <array>
#include <initializer_list>

struct A
{
    A ( std::initializer_list< int > l )
        : m_a ( l )
    {
    }

    std::array<int,2> m_a;
};

int main()
{
    A a{ 1,2 };
}

但是这会导致出现以下错误:

t.cpp: In constructor ‘A::A(std::initializer_list<int>)’:
t.cpp:7:19: error: no matching function for call to ‘std::array<int, 2ul>::array(std::initializer_list<int>&)’
         : m_a ( l )
                   ^
t.cpp:7:19: note: candidates are:
In file included from t.cpp:1:0:
/usr/lib/gcc/x86_64-pc-linux-gnu/4.8.2/include/g++-v4/array:81:12: note: std::array<int, 2ul>::array()
     struct array
            ^
/usr/lib/gcc/x86_64-pc-linux-gnu/4.8.2/include/g++-v4/array:81:12: note:   candidate expects 0 arguments, 1 provided
/usr/lib/gcc/x86_64-pc-linux-gnu/4.8.2/include/g++-v4/array:81:12: note: constexpr std::array<int, 2ul>::array(const std::array<int, 2ul>&)
/usr/lib/gcc/x86_64-pc-linux-gnu/4.8.2/include/g++-v4/array:81:12: note:   no known conversion for argument 1 from ‘std::initializer_list<int>’ to ‘const std::array<int, 2ul>&’
/usr/lib/gcc/x86_64-pc-linux-gnu/4.8.2/include/g++-v4/array:81:12: note: constexpr std::array<int, 2ul>::array(std::array<int, 2ul>&&)
/usr/lib/gcc/x86_64-pc-linux-gnu/4.8.2/include/g++-v4/array:81:12: note:   no known conversion for argument 1 from ‘std::initializer_list<int>’ to ‘std::array<int, 2ul>&&’

这是不可能的,作为一种解决方法,可以手动复制initializer_list的元素:A (std::initializer_list<int> l) /*不要初始化m_a*/ { std::copy(l.begin(),l.end(),m_a.begin());} - Mankarse
请注意,这不仅适用于构造函数;在 std::initializer_list<int> x = { 1, 2 }; std::array<int, 2> m { ?????? }; 中也会出现相同的问题。您只能在此处放置作为聚合初始化的一部分的内容,即每个元素的初始化程序一个接一个地进行。 - M.M
请参见https://dev59.com/NG035IYBdhLWcg3wNtVw,该网页提供了一个可能的解决方案,即使成员数组应该被限定为“const”(这使得将其留空然后稍后复制列表内容不合格)。 - Marc van Leeuwen
1个回答

15
在这种情况下不需要。您可以使用列表初始化来初始化array
std::array<int, 2> a{1,2};

但是你不能使用initializer_list来初始化array,因为array只是一个聚合类型,只有默认构造函数和拷贝构造函数。

你可以让数组保持为空,然后将initializer_list的内容复制到其中。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接