Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::initializer_list ambiguity in Visual Studio

I'm trying to accept a std::initializer_list into a generic constructor like so:

template<typename T>
class Test{
  std::vector<T> V;

  Test(std::initializer_list<T>& list) : V(list){}

};

using

Test<int> test{ 1, 2, 3, 4 };

But I get the error:

error C2440: 'initializing' : cannot convert from 'initializer-list' to 'Test<int>' No constructor could take the source type, or constructor overload resolution was ambiguous

I'm just not sure what I'm doing wrong here.

like image 807
Alex Coats Avatar asked Nov 19 '15 15:11

Alex Coats


1 Answers

Test(std::initializer_list<T>& list) : V(list){}

This takes the std::initializer_list by non-const reference, but you then try to bind a temporary to it, which is illegal

std::initializer_list is designed to be lightweight, so you can just pass it by value:

Test(std::initializer_list<T> list) : V(list){}
//                           ^ no &
like image 154
TartanLlama Avatar answered Nov 12 '22 21:11

TartanLlama