Home > Backend Development > C++ > Why Does a Static Assertion Fail in an Uncalled Template Function?

Why Does a Static Assertion Fail in an Uncalled Template Function?

Susan Sarandon
Release: 2024-11-12 07:58:01
Original
1028 people have browsed it

Why Does a Static Assertion Fail in an Uncalled Template Function?

Static_Assert Failure Despite Uncalled Template Function

Consider the following template function:

template <typename T>
inline T getValue(AnObject&) {
    static_assert(false, "this function has to be implemented for desired type");
}
Copy after login

When compiling with g 4.6.3, despite not calling this function anywhere, the compilation fails with the error:

static_assertion failed "this function has to be implemented for the desired type"
Copy after login

This behavior may raise questions, as the function is not invoked and should not trigger a compilation error. However, according to the C standard in [temp.res]/8:

If no valid specialization can be generated for a template definition, and that template is not instantiated, the template definition is ill-formed, no diagnostic required.
Copy after login

As there is no feasible way to instantiate the function template with a valid specialization that would compile, the template definition itself is considered ill-formed. This allows the compiler to reject it even before any instantiation occurs.

To resolve this issue and allow for delayed error detection, the template function can be modified as follows:

template <typename T>
struct foobar : std::false_type {
};

template <typename T>
inline T getValue(AnObject&) {
    static_assert(foobar<T>::value, "this function has to be implemented for desired type");
}
Copy after login

By using an additional template struct foobar as a compile-time flag, the compiler cannot immediately reject the function template. When instantiated, the relevant specialization of foobar will determine whether the static assertion should fail, as intended.

The above is the detailed content of Why Does a Static Assertion Fail in an Uncalled Template Function?. 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