将函数模板作为参数传递给C ++

时间:2014-08-21 17:35:52

标签: c++ templates

例如,我想从两个序列leftright中获取最大值列表,并将结果保存在max_seq中,这些都是先前定义和分配的,

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

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

 note:   template argument deduction/substitution failed

我知道我可以在struct内或lambda内包装“std :: max”。但有没有办法directly使用std::max没有包装器?

2 个答案:

答案 0 :(得分:6)

std::max有多个重载,因此编译器无法确定您要调用哪个。使用static_cast消除歧义,您的代码将被编译。

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

你应该只使用lambda

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

Live demo

答案 1 :(得分:0)

模板扩展和实例化在编译时发生。因此,您只能将模板功能传递给模板。

你可以在运行时传递一个instanciated(模板化)函数(然后它是一个&#34;普通&#34; C ++函数)。

相关问题