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.

asked Feb 24, 2014 at 15:56
\$\endgroup\$

1 Answer 1

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.

answered Feb 24, 2014 at 16:03
\$\endgroup\$
2
  • \$\begingroup\$ "making this more efficient in C++11" - you mean by adding a overload taking a rvalue reference, right? \$\endgroup\$ Commented 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\$ Commented Feb 24, 2014 at 16:09

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.