Home > Article > Backend Development > 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(); }
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!