如何在C ++中创建适应性函子?

时间:2015-08-18 13:31:45

标签: c++ functor

我必须创建一个接受2个整数参数的仿函数,但仅使用第一个。 我将使用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

1 个答案:

答案 0 :(得分:2)

您已经在行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()应该只有一个参数。
相关问题