Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::remove_if and std::isspace - compile-time error

Tags:

c++

gcc

g++

I have the following code:

#include <algorithm>
#include <cctype>
#include <string>

int main()
{
    std::string str;
    str.erase(std::remove_if(str.begin(), str.end(), std::isspace), str.end());
}

MSVC-11.0 compiles this code without any error, but gcc 4.7.2 gives me the following errors:

main.cpp: In function ‘int main()’:
main.cpp:8:66: error: no matching function for call to ‘remove_if(std::basic_string<char>::iterator, std::basic_string<char>::iterator, <unresolved overloaded function type>)’
main.cpp:8:66: note: candidate is:
In file included from /usr/include/c++/4.7/algorithm:63:0,
                 from main.cpp:1:
/usr/include/c++/4.7/bits/stl_algo.h:1160:5: note: template<class _FIter, class _Predicate> _FIter std::remove_if(_FIter, _FIter, _Predicate)
/usr/include/c++/4.7/bits/stl_algo.h:1160:5: note:   template argument deduction/substitution failed:
main.cpp:8:66: note:   couldn't deduce template parameter ‘_Predicate’

I found this question about it, but according to the cppreference, there isn't any version of this function that takes two arguments. I found this question too, but according to the cppreference (yep, again) I see that there's only one std::isspace function overload.

Who's right? What am I doing wrong? How can I fix it?

like image 315
FrozenHeart Avatar asked Feb 05 '14 13:02

FrozenHeart


1 Answers

There is another overload of std::isspace, so you need to specify which one to use. An easy way is to use a lambda (or write your own one-line function if you don't have C++11 support):

std::remove_if(str.begin(), str.end(), 
               [](char c){ 
                  return std::isspace(static_cast<unsigned char>(c));
               });
like image 65
juanchopanza Avatar answered Oct 12 '22 14:10

juanchopanza