lundi 23 mars 2020

Why should the constructor in std::initializer_list be is this style?

As a novice of c++, I try to learn c++ in other's code. And I notice the guy use the std::initializer_list which I have never used before. So I try to figure out how is this function going, and I notice the example code std::initializer_list like this

template <class T>
struct S {
    std::vector<T> v;
    S(std::initializer_list<T> l) : v(l) {
         std::cout << "constructed with a " << l.size() << "-element list\n";
    }
    void append(std::initializer_list<T> l) {
        v.insert(v.end(), l.begin(), l.end());
    }
    std::pair<const T*, std::size_t> c_arr() const {
        return {&v[0], v.size()};  // copy list-initialization in return statement
                                   // this is NOT a use of std::initializer_list
    }
};

But I have no idea how S(std::initializer_list<T> l) : v(l) this meaning, what is it meaning here? Does it try to initial the Struct as vector? Why it use ':' in here?

And std::pair<const T*, std::size_t> c_arr() const { this line, why the const should be in the last of the line, could it be const std::pair<const T*, std::size_t> c_arr()?

Thanks for anybody who could teach me about this problem!

Aucun commentaire:

Enregistrer un commentaire