在C ++中将函数模板作为参数传递 [英] Pass a function template as a parameter in C++

查看:474
本文介绍了在C ++中将函数模板作为参数传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我想从两个序列中获取最大值的列表, left right ,将结果保存在之前定义和分配的 max_seq 中。

For example, I want to get a list of maximum values from two sequences, left and right, and save the results in max_seq, which are all previously defined and allocated,

std::transform(left.begin(), left.end(), right.begin(), max_seq.begin(), &max<int>);

但这不会编译,因为编译器说

But this won't compile because the compiler says

 note:   template argument deduction/substitution failed

我知道我可以在 struct 里面或者在 lambda 里面封装std :: max。但是有没有办法直接使用 std :: max 没有包装器?

I know I can wrapper "std::max" inside a struct or inside a lambda. But is there a way directly use std::max without wrappers?

推荐答案

std :: max 有多个重载,因此编译器无法确定要调用哪个。

std::max has multiple overloads, so the compiler is unable to determine which one you want to call. Use static_cast to disambiguate and your code will compile.

static_cast<int const&(*)(int const&, int const&)>(std::max)

[](int a, int b){ return std::max(a, b); }

现场演示

这篇关于在C ++中将函数模板作为参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆