Anyone give me an example to use the following constructor int Qt?
QVector::QVector(std::initializer_list<T> args);
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 .
The QVector class is a template class that provides a dynamic array.
The initializer list is used to directly initialize data members of a class. An initializer list starts after the constructor name and its parameters.
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:
Passing a QVector
argument:
void foo(QVector<int>);
foo({1, 2, 3, 4, 5});
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-qualifiedstd::initializer_list<E>
for some typeE
, 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.[...]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With