简体   繁体   中英

How std::initializer_list Works?

I am currently studying c++11 i did not understand constructor of std::initializer_list it looks like this

constexpr initializer_list() noexcept : _First(nullptr), _Last(nullptr) {}

constexpr initializer_list(const _Elem* _First_arg, const _Elem* _Last_arg) noexcept
    : _First(_First_arg), _Last(_Last_arg) {}

But How it works with

std::initializer_list<int> v{1,2,3,4,5,6,7,8,9,0};

and i tried this

constexpr init(const _Elem* _First_arg, const _Elem* _Last_arg) noexcept
    : _First(_First_arg), _Last(_Last_arg) {}

but this shows error

init<int> ob{1,2,3,4,5,6,7,8,9,0}; //this shows error

 note: candidate: 'constexpr init<_Elem>::init(const _Elem*, const _Elem*) [with _Elem = int]'
 constexpr init(const _Elem* _First_arg, const _Elem* _Last_arg) noexcept
           ^~~~
 note:   candidate expects 2 arguments, 10 provided

and i changed {} to () like

std::initializer_list<int> v(1,2,3,4,5,6,7,8,9,0);

This shows error.

1)How std::initializer_list works?

2)What is behind {}?

Thanks.

std::initializer_list is special. It is impossible to write a class that could be used as a constructor argument in the same way. The language rules specify how std::initializer_list works - or rather, how constructors that accept std::initializer_list ie initializer-list constructors work. And the language implementation makes it work as specified.

PS Identifiers such as _Elem are reserved to the language implementation. Since your class init is not part of the language implementation, using reserved identifiers results in undefined behaviour. Don't use reserved identifiers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM