mercredi 4 octobre 2017

c++11 single element vector initialization in a function call

Consider the following example code:

Example:

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

void print(vector<int> vec) {
    cout << "vector print\n";
}

int main() {
   /* call 1 */ print(2);
   /* call 2 */ print({2});
   std::vector<int> v = {2};
   /* call 3 */ print(v);
   /* call 4 */ print( std::vector<int>{2} );
   return 0;
}

which generates the following output:

element print
element print
vector print
vector print

Why the call to print function (call 2 in above example) is getting matched to function accepting a single value? I am creating a vector (containing a single element) in this call, so should it not match to call to print with vector as input?

This is partially discussed in an other question where the provided solution works for vectors with more than 1 elements.

Aucun commentaire:

Enregistrer un commentaire