Search code examples
c++scopescope-resolution

Scope resolution operator for isalnum


I am asking this as a follow-up to this question. The previous question was asked almost three years ago, so I though asking a new one would be better.

The crux of that question I linked to is that the OP tried to run the following line of code:

find_if(s.begin(), s.end(), isalnum);

on some container s. The line of code failed to compile, and the OP should have done this

find_if(s.begin(), s.end(), ::isalnum);

The accepted answer states that there are isalnum functions in the locale and cctype libraries, and that the compiler is having trouble disambiguating between the two, hence the :: scope resolution operator. I tested it by including only one of those libraries, and the compiler is still having issues disambiguating. Why is that? If I included only one of those libraries, then obviously the compiler shouldn't "know" about the other library, so why the conflict?

The second part of my question, is how does the :: operator tell us which isalnum function we want?

Thanks

EDIT

I know that the :: operator tells us that the function/variable we want is in the global scope, but that still doesn't answer my second question.


Solution

  • The isalnum from <locale> is defined in namespace std. The isalnum from <cctype> is defined in namespace std and globally, because symbols from the C library are (probably [1]) made available in global scope. Using ::isalnum requests the version of isalnum from the global scope, and not from namespace std.

    [1]. The standard guarantees that if you include <ctype.h> then the symbols will be at global scope. For the C library headers, this is almost always the case for the cc* versions too, although strictly it is implementation defined.