HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppMinor

Could this template function be improved?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
thistemplateimprovedfunctioncould

Problem

I'm writing wrapper functions for some of the functions in `.
While the following works perfectly, I'm not sure if this is the best way to approach it:

template
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.

Solution

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.

Context

StackExchange Code Review Q#42671, answer score: 3

Revisions (0)

No revisions yet.