Supremum
Supremum

Reputation: 552

Difference in behaviour between clang and gcc when using a function definition as a friend declaration

When compiling the following code with the compilation options "-std=c++17 -pedantic-errors" the compilation gives an error with gcc but no errors with clang (see compiler explorer links below). How is this possible? Is this undefined behaviour or does one of the compilers have a bug? Note that I am compiling with "-pedantic-errors" so the difference should not be because of a compiler extension.

template<typename T>
void f()
{
}

class C
{
    friend void f<int>()
    {
    }
};

int main()
{
}

Run on https://godbolt.org

This is the compilation that gcc generates:

<source>:8:17: error: defining explicit specialization 'f<int>' in friend declaration
    8 |     friend void f<int>()    
      |                 ^~~~~~
<source>:8:17: error: ambiguating new declaration of 'void f()'
<source>:2:6: note: old declaration 'void f() [with T = int]'
    2 | void f()
      |      ^

Upvotes: 4

Views: 254

Answers (1)

Davis Herring
Davis Herring

Reputation: 40043

[dcl.meaning]/1 is supposed to forbid this:

An unqualified-id occurring in a declarator-id shall be a simple identifier except for […] and for the declaration of template specializations or partial specializations ([temp.spec]).

One could argue that this is in fact the declaration of a “template specialization”, and that the cross reference is not sufficient to restrict the form of the declaration to one of those described in that subclause. However, given that no such declaration is permitted outside a class (even by Clang), it’s much more reasonable to just call it a bug.

Upvotes: 1

Related Questions