llvm / llvm/llvm-project

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

Open
#163,514 6 comments 0 reactions 0 assignees View on GitHub
clang:frontend cwg-issue diverges-from:edg diverges-from:gcc diverges-from:msvc
Dominant language
LLVM
Stars
40.5k
Forks
18.7k
PR merge metrics
PR metrics pending

Description


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:

``` cpp
int g(){return 0;};

template
struct R {
friend auto g() {
return M;
}
};
```

Clang output:
```
:5:15: error: functions that differ only in their return type cannot be overloaded
5 | friend auto g() {
| ~~~~ ^
: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:
```cpp
int g() { return 0; }

template
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()`.

Contributor guide

Open the contributing guide

Research direction

Reproduce the supplied class-template examples with Clang and compare them with the GCC, MSVC, and EDG results, including the accepted decltype(M) variant. Trace Clang's handling of friend functions with deduced auto return types; done means the first example is accepted without the return-type redefinition diagnostic while existing behavior remains intact.

Written by the indexing model from the issue text.

Assessment

Tech stack
cpp
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.