为什么这个初始化列表无法匹配模板参数?

3
#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"});
}

错误信息(使用g++ -std=c++17)如下:
error: no matching function for call to ‘Foo::Foo(<brace-enclosed initializer list>)’

这个可以运行

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

为什么initializer-list不能匹配模板构造函数?
2个回答

4

{"foo", "bar", "baz"}没有类型,因此无法推断其类型

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

您只能将其用于扣除。

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

1
正如Jarod42所解释的那样,{"foo", "bar", "baz"}没有类型,因此无法推导出template <typename Container> Foo (const Container&)的类型。
另一个可能的解决方案是:
template <typename T, std::size_t N>
Foo (T const (& arr)[N])
{
    for (auto arg : arr)
        std::cout << "ARG(" << arg << ")\n";
}

所以{"foo", "bar", "baz"}被推断为一个具有正确大小(3)的C风格数组的初始化列表。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接