Consider the code below:
#include <iostream>
#include <vector>
void f(std::vector<int> v) {std::cout << __PRETTY_FUNCTION__ << std::endl;}
void f(int n) {std::cout << __PRETTY_FUNCTION__ << std::endl;}
int main()
{
f({42});
}
Live on Coliru
I was a little surprised to realize that in this case int overloading occurs, i.e. program output:
void f (int)
with warning
warning: brackets around the scalar initializer [-Wbraced-scalar-init] f ({42});
Of course, this only happens when I pass a list of 1 element as an argument, otherwise an overload occurs std::vector.
Why is it {42}treated as a scalar and not as an init-list? Is there a way to get the compiler to choose overload std::vector(without explicit build std::vector<int>{42}) even on lists with 1 element?
PS: std::vectorhas an initialization list constructor
vector(std::initializer_list<T> init, const Allocator& alloc = Allocator());
. (7) cppreference.