C++11 static_assert and template instantiation

后端 未结 5 1024
执念已碎
执念已碎 2020-11-29 03:41

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

5条回答
  •  情深已故
    2020-11-29 04:39

    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
    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::value, with getvalue being a class template (one could specialize it, so the compiler cannot possibly know the boolean value already).

提交回复
热议问题