Consider the following example code:
Example:
void print(int n) {
cout << \"element print\\n\";
}
void print(vector
Because the 1st overload wins in the overload resolution for print({2});.
In both cases copy list initialization applies, for the 1st overload taking int,
(emphasis mine)
Otherwise (if
Tis not a class type), if the braced-init-list has only one element and eitherTisn't a reference type or is a reference type that is compatible with the type of the element,Tis direct-initialized (in direct-list-initialization) or copy-initialized (in copy-list-initialization), except that narrowing conversions are not allowed.
{2} has only one element, it could be used to initialize an int as the argument directly; this is an exact match.
For the 2nd overload taking std::vector,
Otherwise, the constructors of
Tare considered, in two phases:
- All constructors that take
std::initializer_listas the only argument, or as the first argument if the remaining arguments have default values, are examined, and matched by overload resolution against a single argument of typestd::initializer_list
That means an std::initializer_list is constructed and used as the constructor's argument of std::vector (to construct the argument for print). One user-defined conversion (via the constructor of std::vector taking one std::initializer_list) is required, then it's worse match than the 1st overload.