Skip to content

[Clang]Clang rejects friend auto function inside class template when a same-named global function exists (accepted by GCC/MSVC/EDG) #163514

@Attacker23

Description

@Attacker23

When a class template defines a friend auto function and a global function with the same name exists, Clang rejects the code with a redefinition error, while GCC, MSVC, and EDG all accept it:

int g(){return 0;}; 

template<int M>
struct R {
  friend auto g() {
    return M;
  }
};

Clang output:

<source>:5:15: error: functions that differ only in their return type cannot be overloaded
    5 |   friend auto g() {
      |          ~~~~ ^
<source>:1:5: note: previous definition is here
    1 | int g(){return 0;}; 
      | ~~~ ^
1 error generated.
Compiler returned: 1

(See it live: https://godbolt.org/z/E5a1hsfsj)

This is strange. Maybe when a friend function inside a class template uses an auto return type and there exists a global function with the same name, Clang performs conflict checking too early.

Because the following code:

int g() { return 0; }

template<int M>
struct R {
  friend decltype(M) g() {
    return M;
  }
};

is accepted by all compilers, including Clang. https://godbolt.org/z/ecdYTc6vE

This suggests that Clang performs name lookup / overloading checks too early — before the return type of the friend auto function has been deduced.
Once deduced, the function should be considered a distinct friend, not an overload of the global g().

Metadata

Metadata

Assignees

No one assigned

    Labels

    clang:frontendLanguage frontend issues, e.g. anything involving "Sema"cwg-issueAn issue that was filed to the Core Working Groupdiverges-from:edgDoes the clang frontend diverge from edg compiler on this issuediverges-from:gccDoes the clang frontend diverge from gcc on this issuediverges-from:msvcDoes the clang frontend diverge from msvc on this issue

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions