Reputation: 77
I've got class funciton Find. This function have to accept some variables and sometimes (pointer to) another function which will be used inside. How I should declare it?
class CRoute
{
...
list<_T> Find(_T u1, _T u2, ????){
if (????) {...}
}
...
}
have to accept:
X.Find ( "Wien", "Berlin" );
X.Find ( "Wien", "Munchen", TrainFilterCompany ( set<string> { "CD", "DB" } ) );
X.Find ( "Wien", "Munchen", TrainFilterSpeed ( 120, 200 ) );
X.Find ( "Wien", "Munchen", [] ( const CTrain & x ) { return x . m_Company == "CD"; } );
(funtions returns bool)
(_T in this case is string)
Upvotes: 2
Views: 110
Reputation: 3103
You can define a template method taking any callable object (which would support lambdas with captures as well as passing in a reference to an external function):
template <typename Filter>
list<_T> Find(_T u1, _T u2, Filter filter) {
if (filter(obj)) ...
}
// Overload taking no filter and returning everything
list<_T> Find(_T u1, _T u2) {
return Find(u1, u2, [](const CTrain&) -> bool { return true; });
}
You can also use something like std::function<bool (const CTrain&)>
. This would incur a slight overhead of a dynamic allocation when passing in a callable object, but it wouldn't result in code explosion if the Find method is particularly complex.
Upvotes: 3