template problem & remove_if
-
I have a lot of the following in my code:
list.erase (remove_if (list.begin (), list.end (), ToDelete ()), list.end ());
Which just removes entries, if the predicate is met. Trying to be a bit smart, I tried wrapping this up in a nice little template to make it look nicer:template<class Input, class Predicate> void erase_if (Input input, Predicate p) { input.erase (remove_if (input.begin (), input.end (), p), input.end ()); }
All looks great, only it doesnt remove any entries and I cant figure out why. It's probably something obvious, so any ideas? -
I have a lot of the following in my code:
list.erase (remove_if (list.begin (), list.end (), ToDelete ()), list.end ());
Which just removes entries, if the predicate is met. Trying to be a bit smart, I tried wrapping this up in a nice little template to make it look nicer:template<class Input, class Predicate> void erase_if (Input input, Predicate p) { input.erase (remove_if (input.begin (), input.end (), p), input.end ()); }
All looks great, only it doesnt remove any entries and I cant figure out why. It's probably something obvious, so any ideas?Need to pass input into your function by reference:
void erase_if (Input& input, Predicate p)
But the compiler might have trouble matching that function signature to a template function (I don't know exactly what the rules are). Perhaps if you wrote the function assuming Input was a pointer type, so you would useinput->erase (remove_if (input->begin (), input->end (), p), input->end ());
That way the compiler would be forced to treat it as passed by reference, and you'd be forced to code it that way. -
Need to pass input into your function by reference:
void erase_if (Input& input, Predicate p)
But the compiler might have trouble matching that function signature to a template function (I don't know exactly what the rules are). Perhaps if you wrote the function assuming Input was a pointer type, so you would useinput->erase (remove_if (input->begin (), input->end (), p), input->end ());
That way the compiler would be forced to treat it as passed by reference, and you'd be forced to code it that way.