I need to designe predicate for stl algorithms such as find_if, count_if.
namespace lib { struct Finder { Finder( const std::string& name ): name_( name ) { } template< typename TElement > bool operator( const TElement& element ) { return element.isPresent( name_ ); } /* template< typename TElement > bool operator( const TElement& element ) { const Data& data = element.getData(); return data.isPresent( name_ ); }*/ }; }
But I need it to have different operators () according to presence of some certain methods in TElement. Like if it has ‘getData’ I’d like to check that data and if it hasn’t I’d do some other actions.
I am aware of SFINAE. But I don’t have boost:: on the project. So either there is some easy implementation of template ‘has_method’ or you know some other design solution.
I can’t point specific types and simply overload because I’d like to put this Predicate to the one of the project library, which don’t know about those specific classes with ‘getData’ method.
Solution with class traits are good as far as there is no namespaces. Predicate Finder in in ‘lib’ namespace and class with ‘getData’ is in ‘program’ namespace.
Thanks.
Why use template mathods at all? Just use the specific class that you want to base it on or a common base classes if there are lots of class types.
e.g.
If this pattern happens a lot with different class types and you know the types before using the predicate you could template the predicate itself.
e.g.
Or another approach you could use is to use some sort of class traits to hold the information.
e.g.
The downsides of all these methods is that at some point you need to know the types to be able to split them up into which method to use.