Pow*_*101 3 c++ foreach templates stl
我正在尝试使用std :: for_each来输出向量的内容,这些向量可能包含不同的类型.所以我写了一个通用输出函数,如下所示:
template<typename T> void output(const T& val)
{
cout << val << endl;
}
Run Code Online (Sandbox Code Playgroud)
我想用它:
std::for_each(vec_out.begin(), vec_out.end(), output);
Run Code Online (Sandbox Code Playgroud)
但是编译器在for_each语句中抱怨"无法推断出模板参数".还抱怨"函数模板不能成为另一个函数模板的参数".
这不可能吗?我原以为编译器会知道vec_out(它的向量)的类型,所以应该实例化函数"output(const double&val)"?
如果这不起作用,如何在不编写手动循环的情况下获得类似的STL功能?
我对C++很新,还在学习绳索:-)
尝试:
std::for_each(vec_out.begin(), vec_out.end(), output<T>);
Run Code Online (Sandbox Code Playgroud)
where vec_out是一个vector类型为T 的container()
注意:该for_each算法需要最后一个参数的一元仿函数.有关使用仿函数的示例,请参阅链接.
您必须传递模板的实例化.像output<int>你的向量是整数向量的东西.
例如:
template<typename T> void output(const T& val)
{
cout << val << endl;
}
void main(int argc,char *argv[])
{
std::vector<int> vec_out;
std::for_each(vec_out.begin(), vec_out.end(), output<int>);
}
Run Code Online (Sandbox Code Playgroud)
我只想添加正确的答案:如果你将模板函数包装在一个函数对象(aka functor)中,编译器可以推断出类型:
struct OutputFunctor
{
template <typename T>
void operator()(const T& val) const { output(val); }
};
void test()
{
std::vector<int> ints;
std::vector<float> floats;
std::for_each(ints.begin(), ints.end(), OutputFunctor());
std::for_each(floats.begin(), floats.end(), OutputFunctor());
}
Run Code Online (Sandbox Code Playgroud)