简体   繁体   中英

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.

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.

From my understanding using the scope resolution operator (::) helps identify the scope of your program.

So if you had:

Add();     //This is in Global Scope

class Test{
    void Add();       //This is in scope of the "Test" class
    int useAdd(); { ::Add();}
}

So in this case the useAdd() function refers to the add function in global scope rather than the add function within the test class. If you wanted to refer to the one in the test class using the scope resolution operator you would put Test::Add() rather than ::Add() .

In the above case it may be that he had the "isalnum" function implemented both in his current class as well as a global function and he needed to specifically refer to the global function rather than the class function.

EDIT: I think I misunderstood the question, Andrew has answered it better than myself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM