I have an abstract template class
template <typename T>
class Predicate1
{
public:
Predicate1();
virtual ~Predicate1();
virtual bool operator() (const T item) const = 0;
};
an implementation
class Pred : public Predicate1<string>
{
public:
virtual bool operator() (const string item) const;
};
bool Pred::operator()(const string item) const
{
return item == "";
}
and a template class with a method filter that takes a predicate:
template <typename T>
class TList : public boost::enable_shared_from_this<TList<T> >
{
public:
typedef boost::shared_ptr<const TList<T> > List;
const List filter(const Predicate1<T>& p) const;
...
};
I then use the filter as follows:
int main(int argc, char *argv[])
{
const TList<string>::List l1 = ...;
const TList<string>::List l2 = l1->filter(Pred());
}
which works OK.
However, I do not know how to replace the functor with an anonymous function.
I have tried:
const TList<string>::List l2 =
l1->filter([] (const string item) -> bool { return item == ""; });
The anonymous function has, as far as I understand, the same signature as the
functor’s () operator, so it should work. Instead, I get the compiler error:
error: no matching function for call to ‘TList<std::basic_string<char> >::filter(main(int, char**)::<lambda(std::string)>) const’
note: candidate is: const TList<T>::List TList<T>::filter(const Predicate1<T>&) const [with T = std::basic_string<char>, TList<T>::List = boost::shared_ptr<const TList<std::basic_string<char> > >]
So, somehow the types seem to be incompatible, but I do not understand if I have overlooked something or what I am doing wrong. Or in other words, how do I have to declare the filter method so that it can (only) accept an anonymous function with signature
const string -> bool
or, in general, const T -> bool?
Instead of writing your own interface classes, use
std::function:std::functionhas constructors from lambdas and functors, so you can continue to usePred.