llvm-project icon indicating copy to clipboard operation
llvm-project copied to clipboard

clang allows incompatible template constructor for class template argument with default value

Open Rush10233 opened this issue 2 years ago • 2 comments

The following code is accepted by clang but rejected by GCC, EDG and MSVC:

#include<iostream>
template <class K,int NON=0>
struct C    
{      
    int x=0;  
    C<K>(){x=1;};    
};        
int main(){
    C<int> Cont;
    //Cont.x=1
    std::cout<<Cont.x<<std::endl;
    C<int ,100> Cont_2;
    //Cont_2.x=1
    std::cout<<Cont_2.x<<std::endl;    
}

The constructor C<K> seems invalid because it does not explain how the class should be instantiated if the default value of NON is not taken. For example, in the instantiation of Cont_2. As Cont_2.x is set to 1, it seems clang will apply the ctor anyway regardless of whether the default argument value is used.

GCC gives a quite puzzling diagnostic about that:

<source>:6:10: error: expected unqualified-id before ')' token
    6 |     C<K>(){x=1;};
      |          ^
Compiler returned: 1

And the diagnostic provided by EDG seems more reasonable:

"<source>", line 6: error: type used as constructor name does not match type "C<K, NON>"
      C<K>(){x=1;};    
      ^

1 error detected in the compilation of "<source>".
Compiler returned: 2

https://godbolt.org/z/Gz8cvjaYa

Rush10233 avatar Jul 18 '24 13:07 Rush10233

@llvm/issue-subscribers-clang-frontend

Author: None (Rush10233)

The following code is accepted by clang but rejected by GCC, EDG and MSVC:
#include&lt;iostream&gt;
template &lt;class K,int NON=0&gt;
struct C    
{      
    int x=0;  
    C&lt;K&gt;(){x=1;};    
};        
int main(){
    C&lt;int&gt; Cont;
    //Cont.x=1
    std::cout&lt;&lt;Cont.x&lt;&lt;std::endl;
    C&lt;int ,100&gt; Cont_2;
    //Cont_2.x=1
    std::cout&lt;&lt;Cont_2.x&lt;&lt;std::endl;    
}

The constructor C&lt;K&gt; seems invalid because it does not explain how the class should be instantiated if the default value of NON is not taken. For example, in the instantiation of Cont_2. As Cont_2.x is set to 1, it seems clang will apply the ctor anyway regardless of whether the default argument value is used.

GCC gives a quite puzzling diagnostic about that:

&lt;source&gt;:6:10: error: expected unqualified-id before ')' token
    6 |     C&lt;K&gt;(){x=1;};
      |          ^
Compiler returned: 1

And the diagnostic provided by EDG seems more reasonable:

"&lt;source&gt;", line 6: error: type used as constructor name does not match type "C&lt;K, NON&gt;"
      C&lt;K&gt;(){x=1;};    
      ^

1 error detected in the compilation of "&lt;source&gt;".
Compiler returned: 2

https://godbolt.org/z/Gz8cvjaYa

llvmbot avatar Jul 18 '24 15:07 llvmbot

This is basically CWG2237, which applies to C++20 onwards.

Note, gcc reject if we add the second template argument: https://godbolt.org/z/6dxa7Yd8h

shafik avatar Jul 18 '24 16:07 shafik