compile time assertion in c++

Deadly 提交于 2020-01-24 20:41:06

问题


I am reading a compile time assert, after searching online I got some code which I didn't understand.

template <bool> struct CompileAssert {};
#define COMPILE_ASSERT(expr, msg) \
    typedef CompileAssert<(bool(expr))> msg[bool(expr) ? 1 : -1]

Used this COMPILE_ASSERT as below.

COMPILE_ASSERT(!sizeof(T*), PassRefPtr_should_never_be_assigned_to)

But I didnot got the Idea.Can someone help me In understanding the above piece of code. Second got confused on this piece of code

typedef CompileAssert<(bool(expr))> msg[bool(expr) ? 1 : -1]

The #define will replace COMPILE_ASSERT(expr, msg) with above expession.but how msg[bool(expr) ? 1 : -1] a alternative type for CompileAssert<(bool(expr))>.

Please someone explain in detail and simple manner. I have lot many many question.

Like why message(PassRefPtr_should_never_be_assigned_to) work without using "" for char *


回答1:


If you pass an expression to the macro that evaluates to false, the macro will give a typedef like follows:

typedef CompileAssert<false> PassRefPtr_should_never_be_assigned_to[false ? 1 : -1];

which is

typedef CompileAssert<false> PassRefPtr_should_never_be_assigned_to[-1];

So, since negative array lengths are not allowed, the compiler will emit an error for the typedef, containing "msg" as the array name.




回答2:


The typedef will name either a legal or illegal piece of code, based on the value of expr.

Let's say bool(expr) is true. In this case, the typedef is equivalent to

typedef CompileAssert<true> msg[1];

This is a 1-element array of CompileAssert<true> structures, named msg. Since CompileAssert<bool> is a defined structure, all is well.

However, if bool(expr) is false, the typedef will be equivalent to the following:

typedef CompileAssert<false> msg[-1];

This is of course illegal (you can't create an array of size -1), so the compiler will report an error that msg is ill-formed. And because msg is the macro parameter, it will actually be the text provided in COMPILE_ASSERT, so the error message for your example might look something like this:

Cannot create array PassRefPtr_should_never_be_assigned_to of size -1.

Also note that C++11 has a built-in static_assert.



来源:https://stackoverflow.com/questions/16437431/compile-time-assertion-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!