Introduction:
Compiler errors can be perplexing, especially when they arise from calls to functions that are seemingly unused. In this instance, a static_assert statement within a template function is causing compilation failures even though the function is not explicitly called. This article delves into the reasons behind this behaviour and suggests a potential workaround.
Template Function and Compilation Failure:
The template function below triggers a compilation error:
template <typename T> inline T getValue(AnObject&) { static_assert(false , "this function has to be implemented for desired type"); }
Upon compilation, the following error message appears:
static_assertion failed "this function has to be implemented for the desired type"
Reason for Failure:
According to the C Standard (specifically [temp.res]/8), a template definition is deemed ill-formed if no valid specialization can be generated and the template remains uninstantiated. In this case, the compiler encounters no valid specializations for the template function getValue and therefore considers it ill-formed. As a result, the static_assert statement fails compilation, even though the function has not been called.
Possible Workaround:
One possible way to avoid the compilation error while maintaining the intended functionality is to utilize a helper struct:
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"); }
By utilizing the helper struct foobar, the compiler can no longer immediately reject the template function because it cannot determine whether a valid specialization of foobar with value == true will be instantiated later. When the template function is eventually instantiated, the appropriate specialization of foobar is generated, and the static_assert statement fails as expected.
The above is the detailed content of Why Does `static_assert` Fail Compilation Despite an Uncalled Template Function?. For more information, please follow other related articles on the PHP Chinese website!