6.7. Template Parameters as Strategy
Our LessThan class function object of Section 4.9 is a natural candidate for transforming into a template class:
template <typename elemType> class LessThan { public: LessThan( const elemType &val ) : _val( val ){} bool operator()( const elemType &val ) const { return val < _val; } void val( const elemType &newval ) { _val = newval; } elemType val() const { return _val; } private: elemType _val; }; LessThan<int> lti( 1024 ); LessThan<string> lts( "Pooh" );
A potential problem with this implementation is that it fails if the type supplied by the user does not define a less-than operator. One possible strategy is to provide a second template class with the comparison operator factored out of the class definition. ...
Get Essential C++ now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.