STL generic algorithms - implicit conversion of the ranges element type to the predicates parameter type
Say I want to remove all punctuation characters within a std::string
using the erase-remove idiom.
However, let str
be of type std::string
, this call won't compile
str.erase( std::remove_if(str.begin(), str.end(), std::ispunct), str.end() );
Now I guess, strictly speaking the std::ispunct
callables parameter type is int
and therefore doesn't match the ranges element type char
. However, as a char
is a numeric type it should be convertible to int
. I'm working with Lippman's C++ Primer book which states
The algorithms that take predicates call the predicate on the elements in the input range. [...] it must be possible to convert the element type to the parameter type in the input range.
which imo is given in the above statement. Also std::ispunct
returns an int
, and thus should be usable as a condition.
So why does the compiler complain no matching function for call to 'remove_if'
? (clang++ -std=c++11 -o main main.cc
)
A fix would be to use a lambda
str.erase( std::remove_if(str.begin(), str.end(),
[] ( char ch ) { return std::ispunct(ch); }),
str.end() );
still it suprised me that a lambda is necessary...
Thanks in advance!
from Recent Questions - Stack Overflow https://ift.tt/3ie8YZo
https://ift.tt/eA8V8J
Comments
Post a Comment