Implementation of std::initializer_list

后端 未结 3 1405
旧巷少年郎
旧巷少年郎 2021-02-04 01:46

I have been looking at how the initializer_list is implemented so I found section 18.9 of the standard and found a simple enough looking interface. I thought it wou

3条回答
  •  余生分开走
    2021-02-04 01:58

    This answer is not entirely accurate. It is possible to create a fully functional std::initializer_list - it just needs to meet the specific requirements of the target compiler.

    For GCC and clang that requirement is a private ctor. Here is the libc++ implementation (which also happens to work fine with GCC 8.3):

    template
    class initializer_list
    {
        const _Ep* __begin_;
        size_t    __size_;
        
        inline
        constexpr
        initializer_list(const _Ep* __b, size_t __s) noexcept
            : __begin_(__b),
              __size_(__s)
        {}
    public:
        typedef _Ep        value_type;
        typedef const _Ep& reference;
        typedef const _Ep& const_reference;
        typedef size_t    size_type;
        
        typedef const _Ep* iterator;
        typedef const _Ep* const_iterator;
        
        inline
        constexpr
        initializer_list() noexcept : __begin_(nullptr), __size_(0) {}
        
        inline
        constexpr
        size_t    size()  const noexcept {return __size_;}
        
        inline
        constexpr
        const _Ep* begin() const noexcept {return __begin_;}
        
        inline
        constexpr
        const _Ep* end()   const noexcept {return __begin_ + __size_;}
    };
    
    template
    inline
    constexpr
    const _Ep*
    begin(initializer_list<_Ep> __il) noexcept
    {
        return __il.begin();
    }
    
    template
    inline
    constexpr
    const _Ep*
    end(initializer_list<_Ep> __il) noexcept
    {
        return __il.end();
    }
    

提交回复
热议问题