如何使用std::max或std::min作为函数参数



我喜欢将std::maxstd::min传递到函数中。可以编写这样的代码

函数定义

void foo (std::function<double(double, double)> extreme) {
...
const double e = extreme(rhs, lhs);
...
}

On可以使用lambda

调用函数
foo([](const double rhs, const double lhs) { return std::max(rhs, lhs); });

这个很丑。我更喜欢这样写代码

foo(std::max);

不能编译。这个或其他更容易读懂的东西可能吗?

以下作品:

void foo (std::function<double const&(double const&, double const&)>) {}
void foo2 (double const&(double const&, double const&)){}
int main () {
foo((double const&(*)(double const&, double const&))(std::max<double>));
foo2(std::max<double>);
}

注意,我们总是需要使用std::max<double>

在对foo的调用中,因为它需要一个std::function,编译器无法确定使用哪个std::max的重载版本,因此您需要将其强制转换为正确的类型。

对于第二个,由于foo2接受原始函数,它只是工作。

请注意,我已经明确地使用了double const&,因为std::max的普通T版本(因为没有const&)接受初始化器列表,因此没有办法将其强制转换为您需要的内容。

因此,要使它与foo一起工作,您必须使用lambda或过载或某种包装器。

所以最简单的方法是使用上面的知识,并添加重载:

void foo(double const&(*func)(double const&, double const&) )
{
foo([&func](double a, double b){return func(a, b);});
}

,然后foo(std::max<double>);将工作

最新更新