c++ - 将运算符 = 传递给函数对象
问题描述
我尝试通过一个函数对象绑定一个运算符 ()。然后我想将此函数对象用作我声明的映射中的自定义比较器。但我得到以下编译错误
错误 C3867:'Comparator::operator ()':非标准语法;使用“&”创建指向成员 1 的指针> 错误 C2672:“std::bind”:找不到匹配的重载函数
错误 C2923:“std::map”:“predict”不是参数“_Pr”的有效模板类型参数
我不想使用 lamda 表达式
我写的代码如下
#include "pch.h"
#include <algorithm>
#include <functional>
#include <iostream>
#include <map>
struct Comparator : std::binary_function<int const &, int const &, bool>
{
template<typename T>
bool operator()(T const & a, T const & b)
{
return a < b;
}
};
int main()
{
std::cout << "Hello World!\n";
std::function<bool(Comparator&,int const &, int const &)> predict =
std::bind(Comparator::operator(), std::placeholders::_1,
std::placeholders::_2);
std::map<int, int, predict> x;
}
解决方案
绑定后,你会得到带有 2 个参数(int,int)的函子,函数的签名std::function<bool(Comparator&,int const &, int const &)>
是错误的 -Comparator
是多余的,试试这个:
std::function<bool(int const &, int const &)> predict =
std::bind( Comparator(), std::placeholders::_1, std::placeholders::_2);
std::map<int, int, decltype(predict)> x{predict};
推荐阅读
- python - 传递 currentTextChanged 的值
- node.js - 有人可以帮我理解为什么我的弹性 beantalk 在尝试部署应用程序时会出错吗?
- android - RxJava,主题,隐藏
- elasticsearch - 为什么我在这个 ES 搜索中没有得到任何结果?
- github - 将分叉列表保密
- python - 我在 python 中的代码通过不同的数字组合排列有什么问题?
- amazon-web-services - 将 Spark 应用程序部署到 EMR 6.x 时应包括哪些依赖项?
- python - Python - 使用类作为另一个类属性的默认值 - NameError
- python - 使用异步服务器发送多个文件
- javascript - 将数据从数组对象传递到另一个数组