首页 > 解决方案 > 将运算符 = 传递给函数对象

问题描述

我尝试通过一个函数对象绑定一个运算符 ()。然后我想将此函数对象用作我声明的映射中的自定义比较器。但我得到以下编译错误

错误 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;

}

标签: c++operator-overloadingbind

解决方案


绑定后,你会得到带有 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};

推荐阅读