我一直在听C++中的仿函数.有人可以给我一个关于它们是什么的概述以及在什么情况下它们会有用吗?
C++ 函数不能用作作为函子或谓词传递的类型的原因是什么?
函子的主要目的之一是充当函数,以便可以以函数方式调用它。好吧,它可以做更多的事情(有状态等),但是为什么我们不能使用函数而不是函子,因为函子的唯一目的是被调用?
好吧,应该构造对象,对于函子也是如此,但是如果我们看到函数已被传递,则可以跳过这一步。
在下面的代码中,函数和函子的行为类似,直到我尝试将它们传递给 std::map。
#include <algorithm>
#include <map>
#include <ranges>
#include <span>
#include <vector>
bool std_span_less(const std::span<const unsigned int> lhs, const std::span<const unsigned int> rhs) {
return std::ranges::lexicographical_compare(lhs, rhs);
}
struct std_span_less_fn {
bool operator() (const std::span<const unsigned int> lhs, const std::span<const unsigned int> rhs) const {
return std::ranges::lexicographical_compare(lhs, rhs);
}
};
int main()
{
using fn_type = bool (*)(const std::span<const unsigned int> , const std::span<const unsigned int> );
std::vector<unsigned int> lexems = { 0, 1, …Run Code Online (Sandbox Code Playgroud)