STL三大件(迭代器、函数对象、容器)中,函数对象主要起到打辅助的作用。如果把函数对象拿出来单独用真没什么意思,它必须结合抽象算法,以模板参数的形式介入,才能发挥强大的作用。函数对象使[执行策略 参数化]变得可行,实现起来也不复杂。我先给出示例的全部代码,然后再逐一说明。
/* tFind_if.cpp
* created: ume
* date: 2011-12-21
* remarks:
* input:
you are the apple of my eye
^Z
*/
#include<iostream>
#include<vector>
#include<string>
using namespace std;
// function template: tFind_if
template<typename Iterator, typename Predicate>
Iterator tFind_if(Iterator start, Iterator end, Predicate Pred)
{
while(start != end && !Pred(*start))
{
start++;
}
return start;
}
// function pointer
const int len = 4;
bool strlen_gt(const string& s)
{
return s.length() > len;
}
// fun_ptr_to_pred
template<typename arg_t>
class fun_ptr_to_pred
{
bool (*ptr)(arg_t);
public:
typedef arg_t arg_type;
fun_ptr_to_pred(bool (*x)(arg_type)):ptr(x){}
bool operator()(arg_type rhs)
{
return ptr(rhs);
}
};
// auxiliary funcion
template<typename arg_t>
inline fun_ptr_to_pred<arg_t>
to_pred(bool(*pf)(arg_t))
{
return fun_ptr_to_pred<arg_t>(pf);
}
// functional: str_equal
class str_equal
{
string s;
public:
typedef string arg_type;
str_equal(const string& in):s(in){}
bool operator()(const string& rhs)
{
return s == rhs;
}
};
// functional: str_include
class str_include
{
char ch;
public:
typedef string arg_type;
str_include(char c):ch(c){}
bool operator()(const string& rhs)
{
return rhs.find(ch)!= string::npos;
}
};
// function object adapter
template<typename fun_obj>
class reverse_function
{
fun_obj f;
public:
typedef typename fun_obj::arg_type arg_type;
reverse_function(const fun_obj& x): f(x){}
bool operator()(arg_type& a)
{
return !f(a);
}
};
// auxiliary function
template<typename AdaptableFunction>
inline reverse_function<AdaptableFunction>
not(AdaptableFunction& x)
{
return reverse_function<AdaptableFunction>(x);
}
// main function
int main()
{
vector<string> sentence;
string word;
while(cin>>word)
{
sentence.push_back(word);
}
vector<string>::iterator it;
if((it = tFind_if(sentence.begin(),sentence.end(),str_equal("apple"))) != sentence.end())
cout<<"Find the Word: "<<*it<<endl;
else cout<<"No Such Word\n";
if((it = tFind_if(sentence.begin(),sentence.end(),not(str_include('y')))) != sentence.end())
{
cout<<"Word(s) Excluding 'y': "<<*it;
while((it = tFind_if(it + 1,sentence.end(),not(str_include('y')))) != sentence.end())
cout<<", "<<*it;
cout<<endl;
}
else cout<<"No Word Excluding 'y'\n";
if((it = tFind_if(sentence.begin(),sentence.end(),not(to_pred(strlen_gt)))) != sentence.end())
{
cout<<"Word(s) Whose Length <= 4: "<<*it;
while((it = tFind_if(it + 1,sentence.end(),not(to_pred(strlen_gt)))) != sentence.end())
cout<<", "<<*it;
cout<<endl;
}
else cout<<"Length of Every Word > 4\n";
cout<<endl;
system("pause");
return 0;
}
运行结果为:
you are the apple of my eye
^Z
Find the Word: apple
Word(s) Excluding 'y': are, the, apple, of
Word(s) Whose Length <= 4: you, are, the, of, my, eye
请按任意键继续. . .
代码说明:
(1)示例程序的功能: 输入一个字符串,然后调用tFind_if函数对字符串中的单词进行分析,并把符合条件的单词打印出来。
(2)tFind_if的特殊之处在于它不但是函数模板,而且还允许传入函数对象Pred。请观察tFind_if的定义,它回调了Pred(*start),可见Pred是一个单参数函数对象,参数类型为string,返回类型为bool。正因为它的返回值是true或false,所以它本质上是下判断(Predicate)。
(3)暂且跳过函数指针strlen_gt相关的内容,请将注意力移至函数对象str_equal和str_include上。它们本质上是class,实现了括号操作符operator(),而括号操作符可被巧妙地当作函数调用操作符来使用。此外,str_equal的成员string s即基准字符串,在分析字符串中各个单词时,正是将它们与这个基准字符串进行匹配的。str_include的成员ch是基准字符,作用与string s类似。
(4)reverse_function是函数对象适配器,顾名思义,它的作用就是将函数对象的功能进行翻转。这样做的好处是尽可能的减少重复代码,实现功能整合。可以将reverse_function看作函数对象的再一次封装,它本身仍然是class。因此在实际使用的时候,需要写成reverse_function<str_include>(str_include('y'))的形式,非常累赘。毕竟str_include('y')已经隐含了它的类型信息了。所以我们想到使用一个辅助函数来实现模板参数类型的自动推导,这个辅助函数即not()。
(5)好,现在我们将注意力还给函数指针strlen_gt。它是一个参数类型为string、返回类型为bool的指针。实际上strlen_gt已经可以工作了,把它传递给tFind_if没有任何问题,但是面对函数指针形式的strlen_gt,我们却不能对它进行功能翻转。所以,需要实现一种方法将函数指针转换为单参数的函数对象,然后便可以调用reverse_function实现功能翻转了,fun_ptr_to_pred正起到了这个作用。实际上,fun_ptr_to_pred本身是一个函数对象,它是对函数指针的封装。在实际使用的时候需要写成fun_ptr_to_pred<int>(strlen_gt),同样比较累赘,因为strlen_gt已经隐含了int的信息。定义一个类似于not()的辅助函数来实现模板参数类型的自动推导,这个辅助函数即to_pred()。
(6)这些函数对象的使用方法在main函数中有所展示,我偷偷懒不多解释了。欢迎一同讨论!