Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function call not ambiguous if {} is used

#include <stdio.h>
#include <vector>
#include <deque>

// 1st function
void f(int i, int j = 10){
    printf("Hello World what");
};

void f(std::vector<int>){
    printf("Hello World vec");
};

void f(std::deque<int>){
    printf("Hello World deq");
};

int main()
{
    f({});
    return 0;
}

If the 1st function is commented out I get ambiguous call when compiling. If not commented out, 1st function is called. Why is {} implicitly converted to int?

Live example: https://onlinegdb.com/rkhR0NiBD

like image 887
Bill Kotsias Avatar asked Sep 25 '20 09:09

Bill Kotsias


Video Answer


1 Answers

Why is {} implicitly converted to int?

This is copy-list-initialization, as the effect the parameter is value-initialized (zero-initialized) as 0. int could be initialized from (empty) braced-init-list, just as int i{}; or int i = {};.

  1. in a function call expression, with braced-init-list used as an argument and list-initialization initializes the function parameter

For f(std::vector<int>) and f(std::deque<int>) to be called, a user-defined conversion (by the constructor of std::vector and std::deque taking std::initializer_list) is required; then the 1st overload wins in overload resolution.

like image 54
songyuanyao Avatar answered Oct 20 '22 00:10

songyuanyao