Search code examples
c++templatesc++17initializer-listtemplate-argument-deduction

Why can't this initializer-list match to a template argument?


#include <iostream>

class Foo
{
public:

    template <typename Container>
    Foo (const Container & args)
    {
        for (auto arg : args)
            std::cout << "ARG(" << arg << ")\n";
    }
};

int main ()
{
    Foo foo ({"foo", "bar", "baz"});
}

The error (using g++ -std=c++17) is

error: no matching function for call to ‘Foo::Foo(<brace-enclosed initializer list>)’

This works

Foo foo (std::vector<const char*> ({"foo", "bar", "baz"}));

Why can't the initializer-list match the template constructor?


Solution

  • {"foo", "bar", "baz"} has no type, so it cannot be deduced for

    template <typename Container>
    Foo (const Container&);
    

    You can only use it for deduction for

    template <typename T>
    Foo (const std::initializer_list<T>&);