We’ve always been able to use initializer lists with arrays, now you can do it with any type that has a method that takes an argument of type std::initializer_list<T> (including constructors). The standard library collections have all been updated to support initializer lists.
void foo()
{
vector<int> vecint = { 3, 5, 19, 2 };
map<int, double> mapintdoub =
{
{ 4, 2.3},
{ 12, 4.1 },
{ 6, 0.7 }
};
}
And it’s trivial to do this with your own functions.
void bar1(const initializer_list<int>& nums)
{
for (auto i : nums)
{
// use i
}
}
bar1({ 1, 4, 6 });
You can also do it with your user defined types.
class bar2
{
public:
bar2(initializer_list<int> nums) { }
};
class bar3
{
public:
bar3(initializer_list<bar2> items) { }
};
bar2 b2 = { 3, 7, 88 };
bar3 b3 = { {1, 2}, { 14 }, { 11, 8 } };
Uniform initialization is a related feature that’s been added to C++ 11. It automatically uses the matching constructor.
class bar4
{
int x;
double y;
string z;
public:
bar4(int, double, string) { }
};
class bar5
{
public:
bar5(int, bar4) { }
};
bar4 b4 { 12, 14.3, "apples" };
bar5 b5 { 10, { 1, 2.1, "bananas" } };
If there’s an initializer-list constructor, it takes precedence over another matching constructor.
class bar6
{
public:
bar6(int, int) // (1)
{
// ...
}
bar6(initializer_list<int>) // (2)
{
// ...
}
};
bar6 b6 { 10, 10 }; // --> calls (2) above