Forcing std :: vector overloads instead of overloading int in a list with one element

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}); // the int overload is being picked up
}

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.

+4
2

, , {42} - int std::initializer_list<int>. , .

( )

  • , , , - ,

{42} int, void f(int). void f(std::vector<int>) . , void f(int) .

std::vector ( std::vector<int>{42}) 1- ?

, a std::initializer_list<int>, void f(std::vector<int>):

f({{42}});

LIVE

+6

std::vector

int main()
{
    f(std::vector<int>{42}); // the vector overload is being picked up now
}

vector(initializer_list)?

, void f(std::set<int> v).

, , f({1}): a vector a set?

+1

Source: https://habr.com/ru/post/1658389/


All Articles