Pass an unary predicate to a function in C++
Question
I need a function which establishes a policy for my class for displaying items. e.g:
SetDisplayPolicy(BOOLEAN_PRED_T f)
This is assuming BOOLEAN_PRED_T is a function-pointer to some boolean predicate type like:
typedef bool (*BOOLEAN_PRED_T) (int);
I'm interested only on e.g: display something when the passed predicate is TRUE, do not display when it's false.
The above example works for functions returning bool and taking an int, but I need a very generic pointer for the SetDisplayPolicy argument, so I thought of UnaryPredicate, but it's boost related. How I can pass a unary predicate to a function in STL/C++? unary_function< bool,T >
won't work because I need a bool as return value, but I want to ask the user just for "unary function that returns bool", in the most generic approach.
I thought of deriving my own type as:
template<typename T>
class MyOwnPredicate : public std::unary_function<bool, T>{};
Could that be a good approach?
Solution
Turn SetDisplayPolicy
into a function template:
template<typename Pred>
void SetDisplayPolicy(Pred &pred)
{
// Depending on what you want exactly, you may want to set a pointer to pred,
// or copy it, etc. You may need to templetize the appropriate field for
// this.
}
Then to use, do:
struct MyPredClass
{
bool operator()(myType a) { /* your code here */ }
};
SetDisplayPolicy(MyPredClass());
In the display code you would then d someting like:
if(myPred(/* whatever */)
Display();
Of course, your functor may need to have a state and you may want its constructor to do stuff, etc. The point is that SetDisplayPolicy
doesn't care what you give it (including a function pointer), provided that you can stick a function call onto it and get back a bool
.
Edit: And, as csj said, you could inherit from STL's unary_function
which does the same thing and will also buy you the two typedef
s argument_type
and result_type
.
OTHER TIPS
You're on the right track since unary_function is intended as a base class. However, note that the first parameter is supposed to be the argument_type and the second is the result_type. Then, all you need to do is implement operator()
template<typename T>
struct MyOwnPredicate : public std::unary_function<T,bool>
{
bool operator () (T value)
{
// do something and return a boolean
}
}