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

后端 未结 2 1768
逝去的感伤
逝去的感伤 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 <unsigned int D> struct always_false : std::false_type {};
    
    template <typename T, unsigned int D> struct Vec
    {
        static_assert(always_false<D>::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.

    0 讨论(0)
  • 2020-12-21 10:15

    Everything is not 1,2,3,4 (for which specific specializations exist) will go into the "master" definition, that have to assert for every value of D it will be called.

    So you need an expression that contains D and that is always false, to cause the compiler to evaluate it in dependency of D

    If you just use 0, it will be anymore dependent and the compiler will evaluate as it matches during parsing, causing the assertion to always take place. Even if it will not be the class you will instantiate.

    0 讨论(0)
提交回复
热议问题