Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Anyone give me an example to use QVector::QVector(std::initializer_list<T> args)?

Anyone give me an example to use the following constructor int Qt?

QVector::QVector(std::initializer_list<T> args);
like image 360
user1899020 Avatar asked Mar 26 '13 15:03

user1899020


People also ask

What is std :: initializer_list?

std::initializer_list This type is used to access the values in a C++ initialization list, which is a list of elements of type const T .

What is a QVector?

The QVector class is a template class that provides a dynamic array.

What is a initializer list in C++?

The initializer list is used to directly initialize data members of a class. An initializer list starts after the constructor name and its parameters.


1 Answers

A constructor that takes an std::initializer_list is considered when you use list-initialization. That's an initialization that involves a braced initialization list:

QVector<int> v{1, 2, 3, 4, 5};
// or equivalently
QVector<int> v = {1, 2, 3, 4, 5};

Note that this is a C++11 feature. In fact, the first syntax is new to C++11, while the second could have been used in C++03 for aggregate initialization.

You can also use direct-initialization and pass the initializer list as the argument:

QVector<int> v({1, 2, 3, 4, 5});

Since the constructor is not explicit, it can also be used in some other interesting ways:

  1. Passing a QVector argument:

    void foo(QVector<int>);
    
    foo({1, 2, 3, 4, 5});
    
  2. Returning a QVector:

    QVector<int> bar()
    {
      return {1, 2, 3, 4, 5};
    }
    

§8.5.4 List-initialization [dcl.init.list]:

A constructor is an initializer-list constructor if its first parameter is of type std::initializer_list<E> or reference to possibly cv-qualified std::initializer_list<E> for some type E, and either there are no other parameters or else all other parameters have default arguments (8.3.6).

§13.3.1.7 Initialization by list-initialization [over.match.list]:

When objects of non-aggregate class type T are list-initialized (8.5.4), overload resolution selects the constructor in two phases:

  • Initially, the candidate functions are the initializer-list constructors (8.5.4) of the class T and the argument list consists of the initializer list as a single argument.

  • [...]

like image 87
Joseph Mansfield Avatar answered Sep 22 '22 10:09

Joseph Mansfield