如何在c++中创建自适应函子
How to create an adaptable functor in C++?
我必须创建一个接受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_function
和std::unary_function
也已弃用。您不再需要扩展它们。 -
std::count_if
不需要二进制谓词,只需要一元谓词。operator()
应该只有一个参数。
相关文章:
- 自定义创建QFuture
- 如何检查助推融合序列是否为自适应结构
- C++中排序的自适应功能
- Boost.Spirit.Qi 语法,用于 Boost.Fusion 自适应结构中的默认值
- 自适应路径 - 阿斯塔尔修改
- 具有自适应 std::p air 点类型的 R 树查询
- 将自适应阈值应用于范围函数 opencv c++
- 使用C 使用PayPal自适应付款API的最佳方法是什么?
- 将 Rcpp 与 C 代码链接,以实现自适应城域拒绝采样
- 采用 Opencv c++ 的自适应中值滤波器
- 自适应正交 (C++)
- Boost Spirit Parser用三个字符串的矢量编译成一个结构,自适应不工作
- OpenCV / C++ - 如何在矢量上使用自适应阈值而不是垫子
- 您将如何在调度程序中实现这种自适应的"软糖因子"?
- OpenCV中的自适应算法实现
- 用自适应MeanShift对特征空间-SURF描述符进行聚类
- 自适应阈值opencv
- boost::spirit::qi具有相同的简单自适应结构属性的规则会导致编译错误
- 为什么BoostSpirit正确地将标识符解析为std::字符串,而不是解析为仅由std::string组成的自适应结构
- 如何在c++中创建自适应函子