3

Does anyone know why the third way of invoking func doesn't work?

template <typename T>
struct Foo
{
   Foo(T t) {  }
};

template <typename T>
void func(const Foo<T>& f)
{  }

int main(int argc, char *argv[])
{
   func<int>(42);       // works
   func(Foo<int>{42});  // explicit braced initialization works
   func({42});          // implicit braced initialization, doesn't work
   return 0;
}

Ideally, {42} could either be a std::initializer_list<int> or it could be some type which can take an int value. Shouldn't the compiler be able to look at what is being called, what it expects and whether such a conversion is possible?

Praetorian
  • 106,671
  • 19
  • 240
  • 328
skgbanga
  • 2,477
  • 2
  • 20
  • 29
  • How would the compiler figure out whether you intend to use `int`, `Foo`, or `std::initializer_list` as the template parameter? – R Sahu Aug 01 '16 at 22:07
  • I would think that there would be an order of precedence, the way that g(int) vs g(long) is compared. However the type match is exact and no conversion is performed (as seen in the 'possible duplicate' question, 9787593). If there were two constructors of Foo, one with an integer and one with an initializer list, would this give order to the candidates, namely order of definition? As for func(int), only func(const Foo&) is defined, so that should be no problem, right? – John P Aug 01 '16 at 22:20

0 Answers0