Compile-time assertion?

Viewed 45525

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)
12 Answers

you can define your own static assertion , this way :

#include <iostream>
template <bool b> class ClassStaticAssert;
template <>
class ClassStaticAssert<true>{static const bool value = true;};
#define STATIC_ASSERT(e) (ClassStaticAssert<e>())
int main()
{
    STATIC_ASSERT(0);
    return 0;
}
Related