如何在c++中创建自适应函子

How to create an adaptable functor in C++?

本文关键字:自适应 创建 c++      更新时间:2023-10-16

我必须创建一个接受2个整数参数的函子,但只使用first。我将使用std::bind2nd设置第二个参数等于2。但是我不会编译它。

我明白问题是编译器不能在构造函数和二进制函数之间做出选择(我是对的?)。但我不知道怎么补救。

#include <iostream>
#include <functional>
#include <algorithm>
class gt_n : public std::binary_function<int, int, bool>
{
    int val;
public:
    gt_n(int v) : val(v) {}
    bool operator()(int first, int)
    {
        return first > val;
    }
};
int main()
{
    int a[] = { 1, 2, 3 };
    int sz = sizeof a / sizeof a[0];
    gt_n f(2);
    std::cout << std::count_if(a, a + sz,
        std::bind2nd(f(), 2)) << std::endl;
    return 0;
}

编译器消息:

main.cpp: In function 'int main()':
main.cpp:22:18: error: no match for call to '(gt_n) ()'
   std::bind2nd(f(), 2)) << std::endl;
                  ^
main.cpp:5:7: note: candidate is:
 class gt_n : public std::binary_function<int, int, bool>
       ^
main.cpp:10:7: note: bool gt_n::operator()(int, int)
  bool operator()(int first, int)
       ^
main.cpp:10:7: note:   candidate expects 2 arguments, 0 provided

您已经在gt_n f(2);行创建了函子(通过构造函数)。如果将f()传递给std::bind2nd,则尝试调用不存在的operator()()。只需传递函子(f): std::bind2nd(f, 2))

附加说明:

  • 正如在评论中指出的,std::bind2nd已被弃用。您应该使用std::bind。在c++ 11中,std::binary_functionstd::unary_function也已弃用。您不再需要扩展它们。
  • std::count_if不需要二进制谓词,只需要一元谓词。operator()应该只有一个参数。