Is there a way I can assert that two constant expressions are equal at compile time?
e.g. I want this to cause a compile-time error
enum { foo=263, bar=264 }; SOME_EXPRESSION(foo,bar)
but I want this to not cause an error
enum { foo=263, bar=263 }; SOME_EXPRESSION(foo,bar)
edit: the above was simplified. My situation is more like
some_other_file_I_dont_control.h:
class X { public: enum { foo=263 }; }
my_file.h:
enum { bar=something+somethingelse }; // bar should equal X::foo SOME_EXPRESSION(X::foo, bar)
assert(f != must be done at run time. However, an assertion that tests the value of a constant expression, such as the size or offset of a structure member, can be done at compile time.
Of course, the expression in static assertion has to be a compile-time constant. It can't be a run-time value. For run-time values you have no other choice but use the ordinary assert .
What is static assertion? Static assertions are a way to check if a condition is true when the code is compiled. If it isn't, the compiler is required to issue an error message and stop the compiling process. The condition that needs to be checked is a constant expression. Performs compile-time assertion checking.
Assertions in C/C++ Following is the syntax for assertion. void assert( int expression ); If the expression evaluates to 0 (false), then the expression, sourcecode filename, and line number are sent to the standard error, and then abort() function is called.
Yes. You can do this with template specializations on type bool, like this:
// empty default template template <bool b> struct StaticAssert {}; // template specialized on true template <> struct StaticAssert<true> { static void assert() {} }; int f() { StaticAssert<1==1>::assert(); // compiles fine, assert() member found StaticAssert<1==2>::assert(); // compile failure, no assert() member for StaticAssert<false> }
Code is basically from memory, may need some tweaks.
See static_assert
(C++0x only); if on an older version, see Boost's StaticAssert
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With