Why does the `static_assert` always get invoked?

后端 未结 1 1732
孤城傲影
孤城傲影 2021-01-25 23:54

If USE_STATIC_ASSERT is 0, this works as expected (getting indexed type from the list). If 1 the static_assert() is always tripped. I wo

1条回答
  •  时光说笑
    2021-01-26 00:14

    Even if the partial specialization of items that contains the static_assert is not instantiated, the compiler is allowed to reject this code according to §14.6 [temp.res]/p8:

    Knowing which names are type names allows the syntax of every template to be checked. No diagnostic shall be issued for a template for which a valid specialization can be generated. If no valid specialization can be generated for a template, and that template is not instantiated, the template is ill-formed, no diagnostic required.

    To work around that, you can make the expression in static_assert dependent on other class template:

    #include 
    
    template 
    struct AlwaysFalse : std::false_type {};
    
    template 
    struct items
    {
        static_assert(AlwaysFalse{}, "Ran out of Ts.");
        //            ~~~~~~~~~~~~~~~^
    };
    

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