Can the :: operator appear in a context other than resolving the scope when searching for a qualified name?

As a well-known domain resolution operator, used for keyword searches. But what is the value returned by :: ? As I understand it, this is a postfix unary operator. Consider the following:

 namespace A { //something } A:: //error: expected unqualified-id before 'int' int main(){ } 

Can you explain this behavior?

+6
source share
4 answers

The region resolution operator :: is only a syntactic operator and has no other semantics. That is, there are operators that only contribute to the syntax of the language and others, which also contribute to the implementation of semantics / runtime of the program, and this semantics can be customized. This is operator overload.

+5
source

As far as I know, the only value of the operator (not overloaded) :: is region resolution. Your code is interpreted as A::int main() , which generates an error.

+2
source

The region resolution operator :: used only as, well ... the region resolution operator.

In particular, the C ++ grammar, as indicated in the standard in ยง 5.1.1 / 8, is as follows:

 qualified-id: nested-name-specifier template(opt) unqualified-id nested-name-specifier: :: type-name :: namespace-name :: decltype-specifier :: nested-name-specifier identifier :: nested-name-specifier templateopt simple-template-id :: 

In your case, nested-name-specifier has the form namespace-name :: , in particular A :: . For a qualified-id you need at least unqualified-id .

An unqualified-id has the following grammar, according to ยง5.1.1:

 unqualified-id: identifier operator-function-id conversion-function-id literal-operator-id ~ class-name ~ decltype-specifier template-id 
+2
source

The region resolution operator :: is not a function call, it is built on the language and is used by the compiler to search for names, it will return the type that is on the right.

Excerpt from the standard:

The enclosed qualifier name denoting a class, optionally followed by a keyword pattern (14.2), and then followed by the name of a member of either this class (9.2) or one of its base classes (clause 10), is a qualified identifier; 3.4.3.1 describes the name lookup for members of a class that appear in qualified identifiers. The result is a member. The type of result is the type of the element.

In your case, the compiler looks up A :: INT which is clearly not what you would like.

A simple example:

 int count = 0; int main(void) { int count = 0; ::count = 1; // set global count to 1 count = 2; // set local count to 2 return 0; } 
0
source

Source: https://habr.com/ru/post/970142/


All Articles