Why static_assert in template gives me different result with equivalent expressions?

后端 未结 2 1767
逝去的感伤
逝去的感伤 2020-12-21 09:36

I\'ve noticed strange behavior of static_assert:

#include 

template  struct Vec
{
    static_         


        
2条回答
  •  失恋的感觉
    2020-12-21 10:10

    §14.6 [temp.res]/p8:

    If no valid specialization can be generated for a template, and that template is not instantiated, the template is ill-formed, no diagnostic required.

    In both cases no valid specialization can be generated for the primary template due to the static_assert (D && 0 is never true no matter the value of D). Since no diagnostic is required, the compiler is free to diagnose one (when you use 0) but not the other (when you use D && 0).

    Workaround:

    template  struct always_false : std::false_type {};
    
    template  struct Vec
    {
        static_assert(always_false::value, "Invalid dimension for vector!");
    };
    

    The compiler can no longer reject this at definition time, as there might be an explicit specialization of always_false whose value member is true.

提交回复
热议问题