How does the following code work?
#define TYPE_CHECK(T, S) \
开发者_JAVA技巧while (false) { \
*(static_cast<T* volatile*>(0)) = static_cast<S*>(0); \
}
I am reading Google v8's code and found the above macro for type check.
However, I do not understand why it works. while(false) never get executed, right? Can someone explain those lines? Thanks
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.
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.
精彩评论