Assessment of static_assert Behavior in Template Instantiation
In this code, a static_assert is employed to validate the value of the non-type template parameter answer. However, the behavior of this assertion varies between gcc and clang:
<code class="cpp">template <int answer> struct Hitchhiker { static_assert(sizeof(answer) != sizeof(answer), "Invalid answer"); }; template <> struct Hitchhiker<42> {};</code>
gcc's Behavior:
gcc only triggers the assertion when instantiating Hitchhiker with a parameter other than 42.
clang's Behavior:
clang raises the assertion error even if the template is not explicitly instantiated.
Standard Interpretation:
The C standard states that if a template has no valid specializations and is not instantiated, the template is considered ill-formed. This means that no diagnostic is required.
Analysis:
Both compilers are correct in their behavior. Clang chooses to provide a diagnostic even though the standard does not require it.
Alternative Approach:
To only permit an answer of 42, the general template can be omitted, and the specialized template defined as follows:
<code class="cpp">template <> struct Hitchhiker<42> {};</code>
The above is the detailed content of Does `static_assert` Behavior Vary in Template Instantiation Between GCC and Clang?. For more information, please follow other related articles on the PHP Chinese website!