Single-Element-Vector Initialization in a Function Call

前端 未结 3 593
抹茶落季
抹茶落季 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 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 list){
        cout << "initializer_list print\n";
    }
    

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

提交回复
热议问题