如何将大括号括起来的初始化列表传递给函数?

How to pass in a brace-enclosed initializer list to a function?

我想编写一个可以与参数一起使用的函数,否则可能会直接出现在基于范围的循环中:

template <typename Iterable>
void sayIt(const Iterable& stuff) {
    for (const auto& e : stuff) {
        cout << e << endl;
    }
}

这适用于 stl 容器和其他类型,但不适用于大括号括起来的初始化程序:

std::vector<std::string> baz(2, "sorry");
sayIt(baz);              // okay
sayIt({"foo", "bar"});   // not okay

有没有办法让这个函数同时适用于两者?

Braced-init-list 没有类型,导致 template argument deduction 失败。

Non-deduced contexts

In the following cases, the types, templates, and non-type values that are used to compose P do not participate in template argument deduction, but instead use the template arguments that were either deduced elsewhere or explicitly specified. If a template parameter is used only in non-deduced contexts and is not explicitly specified, template argument deduction fails.

  1. The parameter P, whose A is a braced-init-list, but P is not std::initializer_list, a reference to one (possibly cv-qualified), or a reference to an array:

您可以将模板参数明确指定为std::initializer_list以绕过推导,

sayIt<std::initializer_list<std::string>>({"foo", "bar"});

或添加另一个重载 std::initializer_list

template <typename T>
void sayIt(std::initializer_list<T> stuff) {
    sayIt<decltype(stuff)>(stuff);
}