在 C++ 如何使用模板函数作为 std::for_each 中的第三个参数?
我正在尝试使用 std::for_each 输出向量的内容,其中可能包含不同的类型。 所以我编写了一个像这样的通用输出函数:
template<typename T> void output(const T& val)
{
cout << val << endl;
}
我想将其与以下一起使用:
std::for_each(vec_out.begin(), vec_out.end(), output);
但编译器在 for_each 语句中抱怨“无法推导模板参数”。 还抱怨“函数模板不能成为另一个函数模板的参数”。
这不可能吗? 我本以为编译器会知道 vec_out 的类型(它是向量),因此应该实例化函数“output(const double& val)”?
如果这不起作用,我如何在不编写手动循环的情况下获得类似的 STL 功能?
我对 C++ 很陌生,仍在学习中:-)
I am trying to use std::for_each to output the contents of vectors, which may contain different types. So I wrote a generic output function like so:
template<typename T> void output(const T& val)
{
cout << val << endl;
}
which I would like to use with:
std::for_each(vec_out.begin(), vec_out.end(), output);
but the compiler complains with "could not deduce template argument" in the for_each statement. Also complains with "A function template cannot be an argument to another function template".
Is this not possible? I would have thought the compiler would know the type of vec_out (it's vector) and so should instantiate the function "output(const double& val)"?
If this doesn't work how can I get similar STL functionality without writing manual loops?
I am quite new to C++ and still learning the ropes :-)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尝试:
其中
vec_out
是 T 类型的容器 (vector
)。注意:
for_each
算法期望其最后一个参数为一元仿函数。 请参阅链接以获取使用函子的示例。Try:
where
vec_out
is a container (vector
) of type T.Note: The
for_each
algorithm expects an unary functor for its last argument. See the link for an example using functors.您必须传递模板的实例化。 如果您的向量是整数向量,则类似
output
。例如:
You have to pass an instantiation of the template. Something like
output<int>
if your vector is vector of integers.For example:
我只想添加正确的答案:如果您将模板函数包装在函数对象(又名函子)中,编译器可以推断出类型:
I'd just like to add to the correct answers: the compiler can deduce the type if you wrap up your template function in a function object (aka functor):