函数指针和函数对象不是同一类型,为何可替换用作同一函数的参数

函数指针和函数对象不是同一类型,为何可替换用作同一函数的参数?

看下面STL std::sort()使用函数指针和函数对象的情形?

// sort algorithm example#include      // std::cout#include     // std::sort#include        // std::vectorbool myfunction (int i,int j) { return (i myvector (myints, myints+8);               // 32 71 12 45 26 80 53 33        // using default comparison (operator <):    std::sort (myvector.begin(), myvector.begin()+4);           //(12 32 45 71)26 80 53 33        // using function as comp    std::sort (myvector.begin()+4, myvector.end(), myfunction); // 12 32 45 71(26 33 53 80)        // using object as comp    std::sort (myvector.begin(), myvector.end(), myobject);     //(12 26 32 33 45 53 71 80)        // print out content:    std::cout << "myvector contains:";    for(std::vector::iterator it=myvector.begin(); it!=myvector.end(); ++it)        std::cout << ' ' << *it;    std::cout << '
';        return 0;}

如果自定义sort()函数呢?

#include bool lesser (int a,int b){return ab;}void mysort(int arr[],int n,bool (*comp)(int a,int b)){    for(int i=0;ib;}    bool operator()(int a,int b){return a>b;}};main(){    int arr[] = {2,7,5,9,3};    int n = sizeof arr / sizeof *arr;    mysort(arr,n,Lesser());    for(int i=0;i

原因在于函数模板调用时,不需显式声明具体类型,编译器可以自动匹配。

std::sort()是一函数模板:

template   void sort (RandomAccessIterator first, RandomAccessIterator last);template   void sort (RandomAccessIterator first, RandomAccessIterator last, Compare comp);

以下是使用了模板技术的sort函数:

#include bool lesser (int a,int b){return ab;}templateclass Lesser{public:    bool operator()(T a,T b){return ab;}   // 演示与下面重载()相同功能    bool operator()(int a,int b){return a>b;}// 函数对象     // 以上两个成员功能一致,无疑后者更简洁,使用方式与函数相同};template     // 需要模板才能传递函数指针或函数对象void mysort(T arr[],T n,Comp comp){    for(T i=0;i());  // 匿名对象    printArr(arr,n);        getchar();}/*2 7 5 9 32 3 5 7 99 7 5 3 22 3 5 7 99 7 5 3 2*/

-End-

发表评论
留言与评论(共有 0 条评论) “”
   
验证码:

相关文章

推荐文章