Skip to content

Instantly share code, notes, and snippets.

@eskil
Created July 10, 2012 01:18
Show Gist options
  • Save eskil/3080398 to your computer and use it in GitHub Desktop.
Save eskil/3080398 to your computer and use it in GitHub Desktop.
Example of how to implement static assert using template specialisation.
template<bool> struct _compile_time_assert;
template<> struct _compile_time_assert<true> {};
#define ctassert(expr) if (0) { int flaming_goat_sausage = sizeof(_compile_time_assert<(bool)(expr)>); flaming_goat_sausage++; }
int main (int argc, char *argv[]) {
ctassert (sizeof (int) == 4);
ctassert ((sizeof (int) == 5) == false);
//BLAM
ctassert (sizeof (int) == 5);
}
/*
eskil@machine:/tmp$ g++ ctassert.cc -Wall -Werror
ctassert.cc: In function ‘int main(int, char**)’:
ctassert.cc:10: error: invalid application of ‘sizeof’ to incomplete type ‘_compile_time_assert<false>’
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment