在c++中传递函数模板作为参数

Pass a function template as a parameter in C++

本文关键字:参数 函数模板 c++      更新时间:2023-10-16

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

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

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

 note:   template argument deduction/substitution failed

我知道我可以在structlambda内包装"std::max"。但是有没有一种方法directly使用std::max没有包装?

std::max有多个重载,因此编译器无法确定您想调用哪一个。使用static_cast来消除歧义,你的代码就可以编译了。

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

你应该用lambda代替

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

现场演示

模板展开和实例化在编译时进行。所以你只能将模板函数传递给模板。

你可以在运行时传递一个实例化的(模板化的)函数(那么它就是一个"普通的"c++函数)。