標準模板庫中容器對初始化列表的支持源自<initializer_list>這個頭文件中initialize_list類模板的支持肺孵。程序員只要#include了<initializer_list>頭文件,并且聲明一個以initialize_list<T>模板類為參數(shù)的構(gòu)造函數(shù)谱煤,同樣可以使得自定義的類使用列表初始化。
在C++11中骆姐,列表初始化是唯一一種可以防止類型收窄的初始化方式偶器。
列表初始化改變了C++中對類型初始化的一些基本模式,將標準程序庫跟語言拉得更近了脑题。這樣的做法有效地統(tǒng)一了內(nèi)置類型和自定義類型的行為件缸。這也是C++11設(shè)計所遵循的一個思想,即通用為本叔遂,專用為末他炊。
std::initializer_list
initializer_list objects are automatically constructed as if an array of elements of type T was allocated, with each of the elements in the list being copy-initialized to its corresponding element in the array, using any necessary non-narrowing implicit conversions.
/// initializer_list
template<class _E>
class initializer_list
{
public:
typedef _E value_type;
typedef const _E& reference;
typedef const _E& const_reference;
typedef size_t size_type;
typedef const _E* iterator;
typedef const _E* const_iterator;
private:
iterator _M_array;
size_type _M_len;
// The compiler can call a private constructor.
constexpr initializer_list(const_iterator __a, size_type __l)
: _M_array(__a), _M_len(__l) { }
public:
constexpr initializer_list() noexcept
: _M_array(0), _M_len(0) { }
// Number of elements.
constexpr size_type
size() const noexcept { return _M_len; }
// First element.
constexpr const_iterator
begin() const noexcept { return _M_array; }
// One past the last element.
constexpr const_iterator
end() const noexcept { return begin() + size(); }
};
/**
* @brief Return an iterator pointing to the first element of
* the initializer_list.
* @param __ils Initializer list.
*/
template<class _Tp>
constexpr const _Tp*
begin(initializer_list<_Tp> __ils) noexcept
{ return __ils.begin(); }
/**
* @brief Return an iterator pointing to one past the last element
* of the initializer_list.
* @param __ils Initializer list.
*/
template<class _Tp>
constexpr const _Tp*
end(initializer_list<_Tp> __ils) noexcept
{ return __ils.end(); }
}
使用initializer_list的實例
/**
* @brief Set value to string constructed from initializer %list.
* @param __l std::initializer_list.
*/
basic_string&
operator=(initializer_list<_CharT> __l)
{
this->assign(__l.begin(), __l.size());
return *this;
}
參考:
stl源碼
《深入理解C++11:C++11新特性解析與應(yīng)用》