Inconsistent Behavior of static_assert with Non-Type Template Parameters Across Compilers
In C , a static_assert can be used to verify conditions at compile time. However, a recent observation has revealed a disparity in the behavior of static_assert when used in conjunction with non-type template parameters across different compilers.
Specifically, the following code snippet:
template
struct Hitchhiker {
static_assert(sizeof(answer) != sizeof(answer), "Invalid answer");
};
template
struct Hitchhiker {};
behaves differently on Clang and GCC when attempting to disable general template instantiation using static_assert. Clang triggers the assert error even when the template is not instantiated, while GCC only raises the error upon instantiation with a parameter value other than 42.
To understand the discrepancy, let's explore the relevant section of the C standard ([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 rule, the primary template Hitchhiker is ill-formed since no valid specialization can be generated. As such, it is not required to issue a diagnostic. However, Clang chooses to provide a diagnostic despite the lack of requirement.
If the intention is to restrict the instantiation to only 42, the recommended approach is to omit the general template definition as follows:
template
struct Hitchhiker {};
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3