Home > Backend Development > C++ > Why Does a Static Assertion Fail Compilation Despite a Null Function Invocation?

Why Does a Static Assertion Fail Compilation Despite a Null Function Invocation?

Barbara Streisand
Release: 2024-11-06 00:09:02
Original
359 people have browsed it

Why Does a Static Assertion Fail Compilation Despite a Null Function Invocation?

Static Assertion Fails Compilation Despite Null Function Invocation

Using g 4.6.3 with the c 0x flag, developers have encountered an unexpected compilation error:

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

Results in:

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

This error occurs despite the function not being invoked anywhere in the code.

Explanation

According to the C standard [temp.res]/8, if no valid specialization can be generated for a template definition that is not instantiated, the template is ill-formed. While the compiler is not obligated to diagnose this error, it is permitted to reject the template.

Resolution

One approach to resolve this issue is to use a type trait to guard the static assertion:

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

With this modification, the compiler cannot reject the template immediately as it needs to instantiate the relevant specialization of foobar to determine the value of the static assertion, which will still fail as intended.

The above is the detailed content of Why Does a Static Assertion Fail Compilation Despite a Null Function Invocation?. 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