How does the following code work?

后端 未结 2 1366
逝去的感伤
逝去的感伤 2020-12-08 14:57
    #define TYPE_CHECK(T, S)                                     \\
    while (false) {                                              \\
      *(static_cast

        
相关标签:
2条回答
  • 2020-12-08 15:42

    Quite a fancy hack - the purpose of the macro seems to be to check if the type S is assignable to (i.e., is a subclass of) the type T. If it is not, the pointer cast from S* to T* will produce a compiler error. The while (false) prevents the code from actually having any other effect.

    0 讨论(0)
  • 2020-12-08 15:48

    Yes, but the compiler still performs syntax & semantic checks on the loop contents. So if something is wrong (i.e. the implicit type conversion from S* to T* is illegal, which happens if T is neither S nor a base class of S), compilation fails. Otherwise, the quality of the resulting machine code is not affected since the optimizer will detect the nonreachable code and remove it silently.

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