Use c ++ function object

Function object is like using the same function Applicable.

For example: a comparison of the class

#include <iostream>
using namespace std ;

class A{                                                                                                        
public :
    int operator() (int a, int b){ 
        return a-b ;
    }   
} ;
int main()
{
    int a=1, b= 2 ; 
    A a1 ;
    int ret = a1(a, b) ;
    cout << ret << endl ;
    return 0;
}

Template used in combination, enables the user to define a function to compare the size of the template class:

#include <iostream>
using namespace std ;
class A{
public :
    int operator() (int a, int b){
        return a-b ;
    }
} ;
template<class T, class T2>                                                                                                                                                                   
class Test {
private :
    T2 comp ;
    T data ;
public :
    int operator==(Test t) {
        bool ret = comp(t.data, data) ;
        if(ret >= 0) {
            return 1 ;
        }
        return 0 ;
    }
    void setData(T t) {
        data = t ;
    }
    int getData() {
        return data ;
    }
} ;
int main()
{
    Test<int, A>tt ;
    Test<int, A>tt1 ;
    tt.setData(10) ;
    tt1.setData(199) ;
    if(tt == tt1) {
        cout << "大于相等" << endl ;
    }
    else{
        cout << "小于"<< endl ;
    }
    return 0;
}
Published 112 original articles · won praise 34 · views 40000 +

Guess you like

Origin blog.csdn.net/qq_41681241/article/details/104111602