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;
    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 the Container requirement, and its value_type must be Copyable. Predicate must be an UnaryPredicate taking value_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\$ 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\$ Feb 24, 2014 at 16:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.