11
是否有可能?用initializer_list初始化一個數組?
#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 l)/ *不要初始化m_a */{std :: copy(l。 begin(),l.end(),m_a.begin());}' –
Mankarse
2015-03-19 11:38:50
請注意,這不是特殊的構造函數; 'std :: initializer_list x = {1,2}; std :: array m {?????? };'。您只能將這些東西放在聚合初始化的一部分,即每個元素的初始化符一個接一個。 –
2015-03-19 11:49:34
請參閱http://stackoverflow.com/q/5549524/1436796,它也提供了一種可能的解決方案,即使成員數組應該被限定爲'const'(這會使得它不爲空,然後再複製列表內容)。 – 2015-03-19 12:37:56