clang allows incompatible template constructor for class template argument with default value
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
@llvm/issue-subscribers-clang-frontend
Author: None (Rush10233)
#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
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