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?
Turn
SetDisplayPolicyinto a function template:Then to use, do:
In the display code you would then d someting like:
Of course, your functor may need to have a state and you may want its constructor to do stuff, etc. The point is that
SetDisplayPolicydoesn’t care what you give it (including a function pointer), provided that you can stick a function call onto it and get back abool.Edit: And, as csj said, you could inherit from STL’s
unary_functionwhich does the same thing and will also buy you the twotypedefsargument_typeandresult_type.