The inexpressive static assertion construct in C++ is usually written as :
// Prototype :
template<bool test>
struct StaticAssert;
// Only specialize the true case :
template<>
struct StaticAssert<true>
{ };
// Any use of StaticAssert<false> will result in an error.
In C++11, static_assert allows for a message to be displayed, describing the error. To replicate this behavior without C++11, we use a full template specialization :
// Prototype :
template<bool test>
struct StaticAssertVerbose;
// Specialize for the true case, with the messages :
template<>
struct StaticAssertVerbose<true>
{
enum
{
INVALID_OPERATION,
OUT_OF_RANGE
// Any other message
};
};
// Specialize for the false case, without the messages :
template<>
struct StaticAssertVerbose<false>
{ };
// A small capsule :
template<int>
struct StaticAssertCapsule
{ };
// Macros for convenience :
#define _JOIN(x, y) x ## y
#define JOIN(x, y) _JOIN(x, y)
#define STATIC_ASSERT_VERBOSE(test, message) typedef StaticAssertCapsule<StaticAssertVerbose<(test)>::##message> JOIN(StaticAssertTest, __LINE__);
// Example :
STATIC_ASSERT_VERBOSE( N<=0, INVALID_OPERATION)
This can be used in both definitions and implementations (at the condition of having only one assertion per line).