Are static_asserts to be evaluated if a member template isn't instantiated?

前端 未结 1 459
醉话见心
醉话见心 2021-01-25 08:58

I\'m thought I understood how a static_assert worked. But when I tried this on a g++ compiler, I started to wonder:

#include 
#incl         


        
相关标签:
1条回答
  • 2021-01-25 09:23

    Writing static_assert(false) is simply ill-formed, because it runs afoul of [temp.res]:

    The program is ill-formed, no diagnostic required, if:
    — no valid specialization can be generated for a template or a substatement of a constexpr if statement (6.4.1) within a template and the template is not instantiated

    You can think of it as - since the static_assert's constant expression isn't dependent, the compiler can just immediately see that it's ill-formed and fire.


    You can either just not provide a definition of fn() for that specialization, or you could do something like:

    template <class T> struct always_false : std::false_type { };
    static_assert(always_false<some_dependent_type>::value, "...");
    

    This would make it hypothetically possible for a valid specialization to be generated, even if nobody should ever specialize always_false.

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