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"); }
Surprisingly, this code fails with the error:
static_assertion failed "this function has to be implemented for the desired type"
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"); }
This modification defers the diagnostic to the instantiation of the appropriate foobar
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!