Search code examples
c++stlpredicate

Correct Way to Define a Predicate Function in C++


I'm trying to write predicate function for use with STL algorithms. I see that they are two ways to define a predicate:

(1) Use a simple function as below:

bool isEven(unsigned int i) { return (i % 2 == 0); }

std::find_if(itBegin, itEnd, isEven); 

(2) Use the operator() function as below:

class checker {  
public:  
    bool operator()(unsigned int i) { return (i % 2 == 0); }  
}; 
    
std::find_if(itBegin, itEnd, checker); 

I have more use for the second type as I usually would like to create a predicate object with some members in it and use them in the algorithm. When I add the same isEven function inside checker and use it as a predicate, I get an error:
3. Syntax which gives error:

class checker { 
    public: 
       bool isEven(unsigned int i) 
       { return (i%2 == 0); }
}; 

checker c; 
std::find_if(itBegin, itEnd, c.isEven); 

Calling c.isEven gives an error during compilation saying undefined reference to some function. Can someone explain why 3. is giving error? Also, I would appreciate any pointers to read about predicate and iterator basics.


Solution

  • I guess it's because the type of c.isEven() is,

    bool (checker::*)(unsigned int) // member function of class
    

    which may not be expected by find_if(). std::find_if should be expecting either a function pointer (bool (*)(unsigned int)) or a function object.

    Edit: Another constraint: A non-static member function pointer must be called by the class object. In your case, even if you succeed to pass the member function then still find_if() will not have any information about any checker object; so it doesn't make sense to have find_if() overloaded for accepting a member function pointer argument.

    Note: In general c.isEven is not the right way to pass member function pointer; it should be passed as, &checker::isEven.