Single-Element-Vector Initialization in a Function Call

前端 未结 3 586
抹茶落季
抹茶落季 2020-12-10 15:43

Consider the following example code:

Example:

void print(int n) {
    cout << \"element print\\n\";
}

void print(vector

        
相关标签:
3条回答
  • 2020-12-10 15:45

    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 T is not a class type), if the braced-init-list has only one element and either T isn't a reference type or is a reference type that is compatible with the type of the element, T is 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<int>,

    Otherwise, the constructors of T are considered, in two phases:

    • All constructors that take std::initializer_list as 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 type std::initializer_list

    That means an std::initializer_list<int> is constructed and used as the constructor's argument of std::vector<int> (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.

    0 讨论(0)
  • 2020-12-10 15:46

    {2} is a legal initializer for a number of types, including int. Overload resolution prefers a type that exactly matches to one that requires further construction.

    0 讨论(0)
  • 2020-12-10 16:08

    No thats not what you do, you`re creating an initializer_list.

    See: http://en.cppreference.com/w/cpp/utility/initializer_list

    Call 1) Single Element is called

    Call 2) initializer_list creates an single int element

    Call 3) A Vector object is given

    Call 4) A Vector object is given

    The Overload resulotion prefers to use the int parameter method before the std::vector parameter method, because there are less type conversions. The int parameter is a direct match, for the vector parameter an additional conversion is needed.

    For example:

    void print(std::initializer_list<int> list){
        cout << "initializer_list print\n";
    }
    

    would result for call 2, that the output is "initializer_list print"

    0 讨论(0)
提交回复
热议问题