jeudi 26 janvier 2017

the implemention of std::initializer_list

I copied the code from header file initializer_list and renamed the class name to my_initializer_list

template<class _E>
    class my_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 my_initializer_list(const_iterator __a, size_type __l)
      : _M_array(__a), _M_len(__l) { }

    public:
      constexpr my_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(); }
    };

and the code:

int main()
{
    my_initializer_list<int> foo = {1,2,3};

    return 0;
}

and get the error:

could not convert '{1, 2, 3}' from '<brace-enclosed initializer list>' to 'my_initializer_list<int>'

My question : How STL implement the initializer_list class?

Aucun commentaire:

Enregistrer un commentaire