unary_function有一个兄弟是binary_function,俩格的区别是一个为了使用一个参数输入的函数对象,另一个适合两个输入参数的函数对象。对于STL不熟悉的人,很难理解为什么好端端的函数对象, 为吗要从它们继承呢?
其实这是因为STL适配器的需要,简单说,如果仅仅是调用此函数对象的方法,那确实不用这些古怪的东西。不过如果您的函数对象需要灵活使用的时候,就会有问题了。我们首先看一下下面程序。
int main()
{
vector<int> vec(10, 1);
int count1 = count_if(vec.begin(), vec.end(), bind2nd(less_equal<int>(),
10)); //求容器中小于等于10的元素个数
int count2 = count_if(vec.begin(), vec.end(), not1(bind2nd(less_equal<in
t>(), 10))); //求容器中不小于等于10的元素个数,正好是上面函数的取反
cout<<count1<<' '<<count2<<endl; //10 0
return 0;
}
一元运算符negate logical_not, 其他逻辑运算符 less greater_equal等等,这些都是用模板的函数对象来实现的,所以要求函数对象都是来自同一个模板基类,才能匹配. 否则,在类型上,C++编译器是无法通过语义的, 而这些函数对象的原型也没法定义.
举一个源码例子:
//一元操作求反
template <class Predicate>
class unary_negate: public unary_function<typename Predicate::argument_type,
bool> {
protected:
Predicate pred; 6. public:
explicit unary_negate(const Predicate& x) : pred(x) {}
bool operator()(const typename Predicate::argument_type& x) const {
return !pred(x);
}
};
如果没有基类模板,这个函数子是没法子定义原型的.
unary_function Struct
An empty base struct that defines types that may be inherited by derived classes that provides a unary function object.
template<class Arg, class Result>
struct unary_function {
typedef Arg argument_type;
typedef Result result_type;
};
Remarks
The template struct serves as a base for classes that define a member function of the formresult_type operator()(const argument_type&) const.
All such derived unary functions can refer to their sole argument type as argument_type and their return type as result_type.
Example
// functional_unary_function.cpp
// compile with: /EHsc
#include <vector>
#include <functional>
#include <algorithm>
#include <iostream>
using namespace std;
// Creation of a user-defined function object
// that inherits from the unary_function base class
class greaterthan10: unary_function<int, bool>
{
public:
result_type operator()(argument_type i)
{
return (result_type)(i > 10);
}
};
int main()
{
vector<int> v1;
vector<int>::iterator Iter;
int i;
for (i = 0; i <= 5; i++)
{
v1.push_back(5 * i);
}
cout << "The vector v1 = ( " ;
for (Iter = v1.begin(); Iter != v1.end(); Iter++)
cout << *Iter << " ";
cout << ")" << endl;
vector<int>::iterator::difference_type result1;
result1 = count_if(v1.begin(), v1.end(), greaterthan10());
cout << "The number of elements in v1 greater than 10 is: "
<< result1 << "." << endl;
}
The vector v1 = ( 0 5 10 15 20 25 )
The number of elements in v1 greater than 10 is: 3.
Requirements
Header: <functional>
Namespace: std