3
\$\begingroup\$

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.

\$\endgroup\$
3
\$\begingroup\$

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.

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ "making this more efficient in C++11" - you mean by adding a overload taking a rvalue reference, right? \$\endgroup\$ – lethal-guitar Feb 24 '14 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 Feb 24 '14 at 16:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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