Inline Friend Functions: Scope and Accessibility
When defining an inline friend function in a class, its scope is primarily influenced by the nearest enclosing namespace. The friend declaration introduces a function name into the namespace, but it does not immediately make the function visible for regular lookup within that scope.
According to the C standard (ISO/IEC 14882:2011), "if a friend declaration in a non-local class first declares a class or function, the friend class or function is a member of the innermost enclosing namespace." This means that the name of the friend function is initially not found through unqualified or qualified lookup within the namespace scope.
Only when a matching declaration is provided in the namespace scope itself, either before or after the class definition that grants friendship, will the function become visible through unqualified lookup. Additionally, the friend function can still be called through argument-dependent lookup, which considers functions from namespaces and classes associated with the argument types.
For example, the code provided in the question defines an inline friend function named baz in the bar class within the foo namespace. However, attempts to call baz from different scopes within the program result in errors because the function is not visible through regular lookup:
Therefore, inline friend functions have limited accessibility and scope. They are primarily known for their ability to access private and protected members of a class without specifying the class name as a qualifier. However, their visibility within the surrounding scope is restricted until a matching declaration is provided in the namespace or through argument-dependent lookup.
The above is the detailed content of How Does the Scope and Accessibility of Inline Friend Functions Work in C ?. For more information, please follow other related articles on the PHP Chinese website!