Search code examples
c++templatesconstructorinitializer-list

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.


Solution

  • 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 &