what's wrong here?
For polymorphism to work, you need to pass the base class by reference (or a pointer, if you want):
bool testIf(T t, Predicate<T> & predicate) ^
With that in mind, the code works for me, although for my taste it smells a bit like Java.
Are there any other ways to do this?
In C ++ 11 or later, lambda would be more efficient, both in terms of performance and code noise. This eliminates the need to define and inherit from the base class and to call a virtual function.
template <class T, class Predicate> bool testIf(T t, Predicate predicate) { return predicate(t); } testIf(s, [](string const & s){return s.length() == 0;});
(Before C ++ 11, you could do the same with a function object. It was a bit more verbose, but still gave a shorter, more efficient code than the inheritance approach.)
source share