Home > Article > Backend Development > Why Does `static_assert` with Non-Type Template Parameters Behave Differently in GCC and Clang?
Static Assert with Non-Type Template Parameter
In C , static_assert is used to check conditions at compile-time. However, different compilers exhibit varying behaviors when using static_assert with non-type template parameters.
Problem:
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>
produces different results when compiled using GCC and Clang. In GCC, the assertion error is only generated when instantiating Hitchhiker with a parameter other than 42. In Clang, the assertion error is generated even when the template is not instantiated.
Modifying the assertion as follows:
<code class="cpp">template <int answer> struct Hitchhiker { static_assert(sizeof(int[answer]) != sizeof(int[answer]), "Invalid answer"); }; template <> struct Hitchhiker<42> {};</code>
results in consistent behavior between both compilers, with the assertion only being checked during template instantiation.
Answer:
According to the C standard ([temp.res]/8), an uninstantiated template with no valid specializations is considered ill-formed, without the requirement for a diagnostic.
Conclusion:
In the case of the original code, GCC chooses to not issue a diagnostic for the uninstantiated template. Clang, on the other hand, decides to emit a diagnostic even though the standard does not require it. The behavior of the modified code is more consistent between compilers as the assertion is only checked when the template is actually instantiated.
It's important to note that the presence or absence of a diagnostic in this scenario does not indicate an error in the code. The uninstantiated template is inherently ill-formed, and any attempt to instantiate it with a non-valid specialization will result in a compilation error.
The above is the detailed content of Why Does `static_assert` with Non-Type Template Parameters Behave Differently in GCC and Clang?. For more information, please follow other related articles on the PHP Chinese website!