Why does the code below compile? I am not specializing a template member function of a template class, so only one template<>
should be used. However, g++ compiles it with no warnings whatsoever, clang++ gives only a warning
warning: extraneous template parameter list in template specialization
template<typename T>
struct S{};
template<> template<> // why can we do this?
struct S<int>{};
int main()
{
}
Templates are a feature of the C++ programming language that allows functions and classes to operate with generic types. This allows a function or class to work on many different data types without being rewritten for each one.
The act of creating a new definition of a function, class, or member of a class from a template declaration and one or more template arguments is called template instantiation. The definition created from a template instantiation is called a specialization.
Instead the programmer can write a C++ template based function that will work with all data types. There are two types of templates in C++, function templates and class templates.
Generics are generic until the types are substituted for them at runtime. Templates are specialized at compile time so they are not still parameterized types at runtime. The common language runtime specifically supports generics in MSIL.
Because the grammar allows it, and there doesn't seem to be anything under the template specialization section that prohibits it:
From [gram.temp]
explicit-specialization:
template < >
declaration
From [gram.dcl]
declaration:
[...]
explicit-specialization
The fact that the grammar is too lax has been in the active issues list (#293) since 2001.
A bug report (filed as PR5559) from a much older version of clang discusses the issue as well. The problem is that gcc and clang both have discrepancies when it comes to whether multiple template declarations are valid during an explicit specialization. Quoth Gabor Greif:
The first error is actually none, clang correctly diagnoses that only one "
template <>
" is needed. But because g++ accepts this and several people (like me) may have the misconception that the number of "template <>
"s is governed by nesting instead of the number of levels being specialized, it may be interesting to reduce the error to a warning and possibly emit a fixit hint.
The disparity could also be caused by the standard's cyclic definition of an explicit specilization (as noted by @user657267).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With