Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compile-time assertion?

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) 
like image 967
Jason S Avatar asked Jul 20 '11 17:07

Jason S


People also ask

Is assert compile time?

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.

Is static assert 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 assert in C++?

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.

How do you assert in C++?

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.


2 Answers

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.

like image 117
Chad Avatar answered Sep 18 '22 06:09

Chad


See static_assert (C++0x only); if on an older version, see Boost's StaticAssert.

like image 34
user541686 Avatar answered Sep 21 '22 06:09

user541686