In C++11, should the operation of static_assert within a template depend on whether that template has been instantiated or not? For example, with the following code
template <int I> void sa() { static_assert(0,"Hello."); } int main(int argc, char *argv[]) { return 0; }
GCC 4.5.0 will fail the assertion, and produce the "Hello." message. The Digital Mars Compiler version 8.42n on the other hand, gives no message.
What is static assertion? Static assertions are a way to check if a condition is true when the code is compiled. If it isn't, the compiler is required to issue an error message and stop the compiling process. The condition that needs to be checked is a constant expression. Performs compile-time assertion checking.
The act of creating a new definition of a function, class, or member of a class from a template declaration and one or more template arguments is called template instantiation. The definition created from a template instantiation to handle a specific set of template arguments is called a specialization.
To instantiate a template class explicitly, follow the template keyword by a declaration (not definition) for the class, with the class identifier followed by the template arguments. template class Array<char>; template class String<19>; When you explicitly instantiate a class, all of its members are also instantiated.
When a function template is first called for each type, the compiler creates an instantiation. Each instantiation is a version of the templated function specialized for the type. This instantiation will be called every time the function is used for the type.
GCC is correct and the other compiler is correct too. Refer to 14.6p8 in the spec
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.
Therefor, a compiler is free to reject the following
template<typename T> void f() { static_assert(0, "may trigger immediately!"); static_assert(sizeof(T) == 0, "may trigger immediately!"); }
If you want to go safe, you have to arrange it so the compiler cannot know until instantiation whether the boolean expression will be true or false. For example, get the value by getvalue<T>::value
, with getvalue
being a class template (one could specialize it, so the compiler cannot possibly know the boolean value already).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With