【问题标题】:Pass a operator = to a function object将运算符 = 传递给函数对象
【发布时间】: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 作为函子类,以获得更多样板和(几乎)没有回报
  • 它明确告诉你需要使用&amp;Comparator::operator()作为std::bind的第一个参数。
  • 为什么不直接使用std::map&lt;int, int, Comparator&gt;bind 这里有什么意义?
  • FWIW,std::less&lt;&gt; 就是这样做的。

标签: c++ operator-overloading bind


【解决方案1】:

您不需要在这里使用std::bind 或 lambda。 Comparator 是一个完全有效的比较器,因此您可以将 x 声明为:

std::map<int, int, Comparator> x;

如果您的实际Comparator 有一些需要初始化的状态,您可以将Comparator 对象传递给std::map 的构造函数:

Comparator cmp{some, constructor, args};
std::map<int, int, Comparator> x{cmp};

【讨论】:

    【解决方案2】:

    绑定后你会得到带有 2 个参数 (int,int) 的函子,函数 std::function&lt;bool(Comparator&amp;,int const &amp;, int const &amp;)&gt; 的签名是错误的 - 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};
    

    【讨论】:

    • 可以直接用Comparator()初始化predict,其实根本不需要predict
    • std::bind 是否保留作为第一个参数传递的临时对象 Comparator() 的所有权?
    • @BiagioFesta 它存储它的副本。
    • @BiagioFesta 是的,std::bind 的所有参数都复制到绑定对象中。
    • 是不使用 decltype 的任何替代方案。我想在 C++98 编译器中使用 boost 移植这段代码
    猜你喜欢
    • 2012-09-05
    • 2015-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多