4

I was trying to explicitly specialize a member function template when i noticed that one such case(given below) compiles fine in clang and msvc but not in gcc. Here is the link for the verification of the same: https://godbolt.org/z/15z4nT5Kx

struct C 
{
    template<typename T> 
    void f()
    {
        
    }
    
    template<> void f<int>()
    {
        
    }
};

int main()
{   
    return 0;
}

As can be seen in the above link clang and msvc compiles the program without any problem but gcc says:

<source>:10:14: error: explicit specialization in non-namespace scope 'struct C'
   10 |     template<> void f<int>()
      |              ^
<source>:10:21: error: template-id 'f<int>' in declaration of primary template
   10 |     template<> void f<int>()
      |                     ^~~~~~

Which compiler is right here?

Jason
  • 36,170
  • 5
  • 26
  • 60

1 Answers1

4

GCC is wrong in rejecting the given code. This can be seen from temp.expl.spec#3 which states that:

An explicit specialization may be declared in any scope in which the corresponding primary template may be defined ([dcl.meaning], [class.mem], [temp.mem]).

This means that we can safely provide the explicit specialization for the member function template f inside the class itself.

Here is the relevant gcc bug report and the CWG issue.

Jason
  • 36,170
  • 5
  • 26
  • 60