I want to write a function that can be used with an argument that otherwise could directly occur in a range-based loop:
template <typename Iterable>
void sayIt(const Iterable& stuff) {
for (const auto& e : stuff) {
cout << e << endl;
}
}
This works fine with stl containers and other types, but not with a brace-enclosed initializer:
std::vector<std::string> baz(2, "sorry");
sayIt(baz); // okay
sayIt({"foo", "bar"}); // not okay
Is there a way to make the function work with both?
auto init = { "foo", "bar" };
and thensayIt(init);
it will work. The compiler is deducinginit
as typestd::initializer_list<const char*>
. But doesn't it doesn't do the same with{ "foo", "bar" }
. Why? – Unworldly