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

CS *_*Pei 5 c++ templates

例如,我想从两个序列中获得最大价值的列表,left以及right和保存的结果max_seq,这是所有以前定义和分配,

std::transform(left.begin(), left.end(), right.begin(), max_seq.begin(), &max<int>);
Run Code Online (Sandbox Code Playgroud)

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

 note:   template argument deduction/substitution failed
Run Code Online (Sandbox Code Playgroud)

我知道我可以在一个struct或一个内部包装"std :: max" lambda.但有没有包装directly使用的方式std::max

Pra*_*ian 6

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

static_cast<int const&(*)(int const&, int const&)>(std::max)
Run Code Online (Sandbox Code Playgroud)

你应该只使用lambda

[](int a, int b){ return std::max(a, b); }
Run Code Online (Sandbox Code Playgroud)

现场演示