【发布时间】:2020-12-04 00:04:00
【问题描述】:
我想编写一个函数,该函数可以与一个参数一起使用,否则该参数可能会直接出现在基于范围的循环中:
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
有没有办法让函数同时工作?
【问题讨论】:
标签: c++ templates stl list-initialization range-based-loop