Home >Backend Development >C++ >Why Do GCC and Clang Differ in Static Assert Behavior for Uninstantiated Templates?
In template programming, it's possible to enforce certain conditions at compile-time using static assertions. However, different compilers can exhibit variations in their behavior when evaluating these assertions, as exemplified by a recent observation.
Consider the following code snippet:
<code class="cpp">template <int answer> struct Hitchhiker { static_assert(sizeof(answer) != sizeof(answer), "Invalid answer"); }; template <> struct Hitchhiker<42> {};</code>
In this example, we attempt to use a static assertion to disable general template instantiation for Hitchhiker. However, upon compilation, it's noted that clang generates an assertion error even when the template is not instantiated, whereas gcc only generates the error when instantiating Hitchhiker with a parameter other than 42.
Further investigation revealed that this discrepancy stems from the following piece of code:
<code class="cpp">template <int answer> struct Hitchhiker { static_assert(sizeof(int[answer]) != sizeof(int[answer]), "Invalid answer"); }; template <> struct Hitchhiker<42> {};</code>
When compiling with this modified code, both compilers exhibit the same behavior: the assertion is triggered only when the general template is instantiated. This behavior aligns with the C standard, as specified in [temp.res]/8:
If no valid specialization can be generated for a template, and that template is not instantiated, the template is ill-formed, no diagnostic required.
According to this passage, if it's not possible to generate a valid specialization for a template and it's not instantiated, the template is considered ill-formed, requiring no diagnostic. In this case, clang chooses to provide a diagnostic, while gcc does not.
To enforce the restriction to only allow 42, one approach is to refrain from defining the general template:
<code class="cpp">template <> struct Hitchhiker<42> {};</code>
The above is the detailed content of Why Do GCC and Clang Differ in Static Assert Behavior for Uninstantiated Templates?. For more information, please follow other related articles on the PHP Chinese website!