Home  >  Article  >  Backend Development  >  Why Does `static_assert` Behave Differently with Non-Type Template Parameters Across Compilers?

Why Does `static_assert` Behave Differently with Non-Type Template Parameters Across Compilers?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-05 09:02:02929browse

Why Does `static_assert` Behave Differently with Non-Type Template Parameters Across Compilers?

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:

<code class="cpp">template <int answer>
struct Hitchhiker {
  static_assert(sizeof(answer) != sizeof(answer), "Invalid answer");
};

template <>
struct Hitchhiker<42> {};</code>

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:

<code class="cpp">template <>
struct Hitchhiker<42> {};</code>

The above is the detailed content of Why Does `static_assert` Behave Differently with Non-Type Template Parameters Across Compilers?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn