Home >Backend Development >C++ >Why Does `static_assert` Fail Compilation for an Uncalled Template Function?

Why Does `static_assert` Fail Compilation for an Uncalled Template Function?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-09 00:35:02600browse

Why Does `static_assert` Fail Compilation for an Uncalled Template Function?

Why Does static_assert Fail Compilation for an Uncalled Template Function?

When using template static_assert, it's expected that the assertion fails only when the template function is instantiated. However, in certain cases, like the one raised below, the compilation fails even before the function is called:

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

Explanation

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."

In the provided template, no valid specialization can be generated because the static_assert condition is always false. Therefore, the template definition is ill-formed. Even though it's not instantiated, the compiler may reject it early.

Solution

To resolve this issue, the template 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");
}

This way, the compiler cannot immediately reject the function template since it needs to instantiate the appropriate specialization of foobar before evaluating the static_assert condition. As a result, the compilation error will only occur when the function is actually instantiated and the assertion fails.

The above is the detailed content of Why Does `static_assert` Fail Compilation for an Uncalled Template Function?. 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