uniform initialization

文章目录
1
2
3
4
5
6
int values[] {1,2,3};
vector<int> v{2,3,5,6,7,11,13};
vector<string> cities {
"beijing", "shanghai","nanjing"
};
complex<double> c{4.0, 3.0};

利用一个事实,编译器看到{t1,t2,…,tn} 便会做出一个 initializer_list, 它关联至一个 array<T, n>。 调用函数(例如 ctor)时改 array 内的元素可被编译器分解逐一传给函数。但若函数参数是个 initializer_list, 调用者却不能基于数个 T 参数然后以为他们会被自动转为一个 initializer_list 传入。

1
2
3
4
5
6
7
void print(std::initializer_list<int> vals)
{
for(auto p = vals.begin(); p != vals.end(); ++p) {
std::cout<< *p <<endl;
}
}
print({1,2,3,4,5,6,7,8});

The initializer_list object refers to the elements of this array without containing them: copy initializer_list object produces another object referring to the same underlying elements, not to new copies of them.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
vector<int> v1 {2,5,7,13,69,83,50};
vector<int> v2({2,5,7,13,69,83,50}); // 调用接收 initializer_list 的构造函数
vector<int> v3;
v3 = {2,5,7,13,69,83,50}; //operator=
v3.insert(v3.begin() + 2, {0,1,2,3,4,5});

cout<< max({1,2,3,4,5}) << endl;
cout<< min({1,2,3,4,5}) << endl;

template<typename _Tp>
inline _Tp min(initializer_list<_Tp> __l) {
return *std::min_element(__l.beigin(), __l.end());
}

template<typename _Tp>
inline _Tp max(initializer_list<_Tp> __l) {
return *std::max_element(__l.beigin(), __l.end());
}