I'm writing wrapper functions for some of the functions in <algorithm>
.
While the following works perfectly, I'm not sure if this is the best way to approach it:
template<class ContainerType, class Predicate>
ContainerType filter(
const ContainerType& container,
Predicate predicate
) {
ContainerType filteredContainer;
std::remove_copy_if(
container.begin(),
container.end(),
std::back_inserter(filteredContainer),
predicate
);
return filteredContainer;
Would you change something about the wrapper? I'm especially worried about the template parameters, e.g. you'll have to read the entire function in order to know what types are valid for predicate
etc.
1 Answer 1
The use of template parameters here is just fine. You can call the second one UnaryPredicate
if that makes you happier, but in the end, C++ currently lacks the ability to specify further requirements on template arguments. (That's what concepts are for.)
So you really need to specify the detailed requirements in prose in the documentation, e.g.
ContainerType
must fulfill theContainer
requirement, and itsvalue_type
must beCopyable
.Predicate
must be anUnaryPredicate
takingvalue_type
as its argument.
What you could possibly improve is making this more efficient in C++11 when the argument is a temporary.
-
\$\begingroup\$ "making this more efficient in C++11" - you mean by adding a overload taking a rvalue reference, right? \$\endgroup\$lethal-guitar– lethal-guitar2014年02月24日 16:06:19 +00:00Commented Feb 24, 2014 at 16:06
-
1\$\begingroup\$ That's one way. Another would be trying advanced template trickery to do it all in one function. Not sure I would want to do that, but it's an option. \$\endgroup\$Sebastian Redl– Sebastian Redl2014年02月24日 16:09:42 +00:00Commented Feb 24, 2014 at 16:09