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

Why Does a Static Assert Fail in an Uncalled Template Function in C 0x?

Mary-Kate Olsen
Release: 2024-11-06 16:42:03
Original
251 people have browsed it

Why Does a Static Assert Fail in an Uncalled Template Function in C  0x?

Static_Assert Failure Despite Uncalled Template Function

In C 0x, templates with unused static_assert declarations may result in compilation failures. Consider the following code:

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

Surprisingly, this code fails with the error:

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

Intuitively, one would expect the compiler to only instantiate the template function if it is called. However, the C standard specifies otherwise in [temp.res]/8:

No diagnostic shall be issued for a template definition for which a valid specialization can be generated. 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.

Since there is no valid specialization that compiles, the compiler is allowed to reject the template definition regardless of whether it is instantiated.

To resolve this issue, one can redefine the code 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 the desired type");
}
Copy after login

This modification defers the diagnostic to the instantiation of the appropriate foobar specialization, ensuring the template definition is well-formed until then.

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