使用std :: greater或std :: less作为参数的参数 [英] Parameter to use std::greater or std::less as argument

查看:2953
本文介绍了使用std :: greater或std :: less作为参数的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用一个参数接受std :: greater< int>或std :: less< int>作为参数。我仍然坚持参数的语法。

I would like to make a function with a parameter that accepts either std::greater<int> or std::less<int> as the argument. I'm stuck on the syntax for the parameter, though.

这是我尝试的格式:

myFunction(int a, int b, bool *comp(int, int)) { … }
…
std::greater<int> bigger;
myFunction(2, 3, bigger);

这不起作用,但我怀疑第三个参数是完全错误的。

That doesn't work*, though, and I suspect the third parameter is just completely wrong. What should it actually be?

*无法将'std :: greater'转换为'bool *(*)(int,int)

*cannot convert ‘std::greater’ to ‘bool* (*)(int, int)

推荐答案

使用比较器的函数通常通过模板实现:

Functions taking a comparator are usually implemented via templates:

template <typename Comparator>
myFunction(int a, int b, Comparator comp) { … }

也使用 std :: function 实现它:

myFunction(int a, int b, std::function<bool (int, int)> ) { … }

第一个版本暴露了标题中的代码,但通常会表现更好。
对于第二个版本,你可以隐藏在.cpp文件中的实现,
,但是你将失去一些性能,因为不能内联
比较器调用。

The first version exposes code in the header but will usually perform better. As for the second version, you can hide the implementation in the .cpp file, but you would lose some performance due to the impossibility to inline the comparator calls.

这篇关于使用std :: greater或std :: less作为参数的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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