【发布时间】:2019-06-12 13:56:34
【问题描述】:
我尝试通过一个函数对象绑定一个运算符 ()。然后我想将此函数对象用作我声明的映射中的自定义比较器。但是我得到以下编译错误
错误 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;
}
【问题讨论】:
-
为什么需要模板化的
operator()? -
为什么不想使用 lambda?你总是可以写一个 lamda 作为函子类,以获得更多样板和(几乎)没有回报
-
它明确告诉你需要使用
&Comparator::operator()作为std::bind的第一个参数。 -
为什么不直接使用
std::map<int, int, Comparator>?bind这里有什么意义? -
FWIW,
std::less<>就是这样做的。
标签: c++ operator-overloading bind