tommyk
tommyk

Reputation: 3307

Will this static assert work correctlly?

I saw recently following code:

#define MY_ASSERT_CONCAT_(a, b) a##b
#define MY_ASSERT_CONCAT(a, b) MY_ASSERT_CONCAT_(a, b)
#define MY_STATIC_ASSERT(e,msg) enum { MY_ASSERT_CONCAT(assert_line_,__LINE__) = 1/int(!!(e)) }

Will it work as expected (BOOST_STATIC_ASSERT-like) ?

Upvotes: 0

Views: 236

Answers (1)

Ajay
Ajay

Reputation: 18431

Would it work for you?

#define MY_STATIC_ASSERT(e,msg) \
{   \
        int MY_ASSERT_CONCAT(assert_line_,__LINE__)[!!e]; \
        MY_ASSERT_CONCAT(assert_line_,__LINE__); \
}

It is trying to declare an array of size 1 or 0, depending on expression. It would work only on VC, since GCC allows zero sized arrays(by default). Second usage is just using the variable, so that compiler wont emit "unused variable" warning. Note that there are no spaces after backslash (\), and it works on VC. Either change it to single line macro, or use appropriate alternative in you compiler.

I recommend using static_assert instead, which will produce elegant error message (and just one error message!).

Upvotes: 1

Related Questions