Static asserts are very convenient for checking things in compile time. A simple static assert idiom looks like this:
template<bool> struct StaticAssert;
template<> struct StaticAssert<true> {};
#define STATIC_ASSERT(condition) do { StaticAssert<(condition)>(); } while(0)
This is good for stuff like
STATIC_ASSERT(sizeof(float) == 4)
and:
#define THIS_LIMIT (1000)
...
STATIC_ASSERT(THIS_LIMIT > OTHER_LIMIT);
But using #define
is not the "C++" way of defining constants. C++ would have you use an anonymous namespace:
namespace {
const int THIS_LIMIT = 1000;
}
or even:
static const int THIS_LIMIT = 1000;
The trouble with this is that with a const int
you can't use STATIC_ASSERT()
and you must resort to a run-time check which is silly.
Is there a way to properly solve this in current C++?
I think I've read C++0x has some facility to do this...
EDIT
Ok so this
static const int THIS_LIMIT = 1000;
...
STATIC_ASSERT(THIS_LIMIT > 0);
compiles fine
But this:
static const float THIS_LIMIT = 1000.0f;
...
STATIC_ASSERT(THIS_LIMIT > 0.0f);
does not.
(in Visual Studio 2008)
How come?