Home > Backend Development > C++ > How Does the Scope of an Inline Friend Function in C Actually Work?

How Does the Scope of an Inline Friend Function in C Actually Work?

Barbara Streisand
Release: 2024-11-25 02:13:21
Original
583 people have browsed it

How Does the Scope of an Inline Friend Function in C   Actually Work?

Scope of Inline Friend Functions

In the context of C , an inline friend function's lexical scope extends to the class it's defined within. However, determining its actual scope requires further exploration.

The ISO C standard specifies that when an inline friend function is declared within a namespace-scoped class, it names a function in the nearest enclosing namespace scope. If the function hasn't already been declared, the friend declaration alone does not make it visible in that scope for unqualified lookup.

Instead, the friend declaration allows the function to be accessed through argument-dependent lookup (ADL). This means that the friend function can be called using its unqualified name as long as the function arguments have types that match the namespace scope containing the function declaration.

Therefore, inline friend functions declared within classes can only be called through ADL, unless they are subsequently declared or defined in their enclosing namespace scope. This ensures that the function can only be accessed when the arguments allow for unambiguous name resolution.

The following code snippet illustrates this behavior:

namespace foo {
  struct bar {
    friend void baz();
  };
}

// Compilation error in main: 'baz' is not accessible through unqualified lookup
int main() {
  foo::baz();
}
Copy after login

The above is the detailed content of How Does the Scope of an Inline Friend Function in C Actually Work?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template