Home > Backend Development > C++ > body text

Why Do GCC and Clang Differ in Static Assert Behavior for Uninstantiated Templates?

Mary-Kate Olsen
Release: 2024-11-04 19:20:01
Original
811 people have browsed it

Why Do GCC and Clang Differ in Static Assert Behavior for Uninstantiated Templates?

Static Assert Behavior Discrepancy between GCC and Clang

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>
Copy after login

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>
Copy after login

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.
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template