Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11 static_assert and template instantiation

Tags:

c++

c++11

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.

like image 522
user2023370 Avatar asked Mar 09 '11 12:03

user2023370


People also ask

What is Static_assert?

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.

What is instantiation of a template?

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.

How do I instantiate a template?

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.

What causes a C++ template function to be 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.


1 Answers

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

like image 86
Johannes Schaub - litb Avatar answered Sep 23 '22 07:09

Johannes Schaub - litb