You are, probably, familiar with run-time asserts, but sometimes the information for the verification is available at compile time, in this case static asserts would help to discover potential errors before you actually run the code.

template<bool> struct CompileTimeError;
template<> struct CompileTimeError<true> {};

#define STATIC_ASSERT(exp) (CompileTimeError< (exp) >()) 

We declared a class CompileTimeError, but actually defined it only for special case where the boo template parameter is true, so this can be used as following:

template<typename T1, typename T2>
void dumb_copy(const T1 from, T2 to) {
   STATIC_ASSERT(sizeof(T2) >= sizeof(T1));
   memcpy(&to, &from, sizeof(T1));

void show_static_assert(void) {
   char c = 'a';
   int i = 10;
   dumb_copy(c, i);
   //dumb_copy(i, c);

The last line in this example will cause compilation error, as the expression sizeof(char) >= sizeof(int) is false, so we will try to create instance of undefined class. There are aslo techniques to make the compiler print more informative error message.

Last edited Nov 29, 2007 at 6:58 PM by migo, version 1


No comments yet.