Tuesday 28 March 2017

c++ - Resolution of function overloading about initializer_list

#include 
using namespace std;

class A
{
public:
explicit A(const initializer_list & a) {}
};
void func(const vector& a)
{

}
void func(A a)
{

}
int main(void)
{
func({ 1,2,3 });
}



This code fails to compile:




(19): error C2668: 'func': ambiguous call to overloaded function



(13): note: could be 'void func(A)'



(9): note: or 'void func(const std::vector> &)'
with[_Ty=int]
(19): note: while trying to match the argument list '(initializer list)'




Note that I specified 'explicit' on A's constructor.



In my view, func(A a) should not be considered as a candidate of {1,2,3}. And actually, it is not. If I remove func(const vector& a), then the code still fails, instead of succeeding by removing ambiguity.



In summary, in this code, the func(const vector& a) is the only callable function for {1,2,3}, so there is no ambiguity.



My question is..




  1. How does C++ overloading resolution procedures come to conclusion of 'ambiguous'?


  2. Why doesn't C++ just simply choose callable one?


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...