Consider the following template function:
template <typename T> inline T getValue(AnObject&) { static_assert(false, "this function has to be implemented for desired type"); }
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"
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.
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"); }
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
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!