Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove_if(str.begin(), str.end(), ::isspace); what does the ::isspace means?

Tags:

c++

stl

I'm recently want to find a way to trim string by using STL. I saw somebody use

remove_if(str.begin(), str.end(), isspace);

I found isspace is a funtion in stl, the header is <ctype.h>. I put the above code and header file in my function, then it could not pass the compile. The compiler is complaining something about isspace.

I try

remove_if(str.begin(), str.end(), std::isspace);

it still could not pass the compilation.

Then I found another guys use

remove_if(str.begin(), str.end(), ::isspace);

I try this, it could pass the compilation.

My question is that

  1. why I could not pass the compilation by using the first two ways.

  2. what does the ::isspace means? Is it want to mention it belongs to the STL or anything else? I am confused about the usage of ::?

like image 841
Teddy Avatar asked Sep 18 '25 00:09

Teddy


2 Answers

std::isspace is an overloaded function in C++, with a template function declared in <locale>. Implementations are allowed to silently include additional headers you didn't ask for, and many do so. They do so because they internally make use of those additional headers.

Normally, the argument passed to std::isspace would determine which overload gets picked, but in your case, you're not passing any argument, you're attempting to merely determine its address.

::isspace works, because that isn't an overloaded function.

It's like

template <typename T>
void f(T) { }

void g(int) { }
void h() { f(g); } // okay, g is not an overloaded function

void i(int) { }
void i(char) { }
void j() { f(i); } // error, the compiler cannot know whether you want the void(int)
                   // function, or the void(char) one

What you have been told in the comments is right, the simple way of making sure it works is by not passing the address of isspace at all, but creating a function of your own that calls isspace. You need to do so anyway for other reasons, but it also nicely avoids the problem entirely.

::isspace means you're explicitly calling the global method isspace. The C Standard Library methods are all globals, and <ctype.h> is a C Standard Library header.

Namespaces don't exist in C, so when using the C library headers, you don't use the std namespace. The C++ counterpart to <ctype.h> which uses the std namespace is <cctype>.

The leading :: notation is useful when you're trying to deal with name conflicts. For example, you could have code like this...

void DoSomething(void);

class Foo {
  void DoSomething (void); // Uhoh, this method shadows the global DoSomething.
  void DoSomethingElse(void) {
    Foo::DoSomething(); // Calls the class local DoSomething()
    ::DoSomething(); // Calls the global DoSomething()
  }
};
like image 27
QuestionC Avatar answered Sep 19 '25 15:09

QuestionC