被一网友问到过个这个问题,看了下源码,差不多应该明白了
例子:
int a[] = {1,3,5,7,9}; std::for_each(std::begin<int>(a), std::end<int>(a), [&](int n) {cout << n;}); //这样会把13579输出来。1,先看一下begin和end这源码
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(); }2.嘿!原来是调用了一个initializer_list这个类模版的begin和end方法,我们可以继续查看
// The compiler can call a private constructor.这个编译器主动调用的构造函数,开发者调用不了 constexpr initializer_list(const_iterator __a, size_type __l) : _M_array(__a), _M_len(__l) { } //size()方法直接返回_M_len,也就是编译器确定的长度 constexpr size_type size() const noexcept { return _M_len; } //begin()方法直接返回_M_array,首地址了 constexpr const_iterator begin() const noexcept { return _M_array; } //end()方法返回的时首地址加上数组长度,即尾端 constexpr const_iterator end() const noexcept { return begin() + size(); }这下应该明白了,是编译器的锅。
更多文章:http://blog.csdn.net/what951006?viewmode=list powered by:小乌龟在大乌龟背上~