[Home]  [Edit this page]  [Recent Changes]  [Special Pages]  [Help
CppCompileTimeAssert

(C++) assert at compile-time

There are two ways to do an assert at compile-time:
  • Using a temporary array
  • Using generic programming
One can also use BOOST_STATIC_ASSERT from the Boost C++ Librray.

Using a temporary array

The trick to this method is that an array cannot be of size zero. This method can also be used in C.

  1. define STATIC_ASSERT(x) { const char temp[ (((x) == 0) ? 0 : 1) ] = {'\0'}; }
int main() { STATIC_ASSERT( 1 + 1 == 2 ); //The line below will give the following compile-time error: // [C++ Error] : Array must have at least one element //STATIC_ASSERT( 1 + 2 == 2 ); }


Using generic programming

template <bool> struct CompileTimeAssert;
template<> struct CompileTimeAssert<true> {};
int main()
{
  CompileTimeAssert<((1+1)==2)> x;
  //The line below will give the following compile-time errors:
  //  [C++ Error] : Undefined structure 'CompileTimeAssert<0>'
  //  [C++ Error] : Size of 'y' is unknown or zero
  CompileTimeAssert<((1+2)==2)> y;
}


The trick is that the only existing struct CompileTimeAssert<> is CompileTimeAssert<true>. Therefore, the part between < > must be true!

'Compile time assert' links



last edited (May 28, 2007) by bilderbikkel, Number of views: 3104, Current Rev: 7 (Diff)

[Edit this page]  [Page history]  [What links here]  [Discuss this topic]  [Printer Friendly]  

Members

Username:

Password:


Register
Forgot Password?




Programmers Heaven - for .NET, Java, C/C++ and WEB Developers!
© 1996-2008 Community Networks Ltd. All rights reserved. Reproduction in whole or in part, in any form or medium without express written permission is prohibited. Violators of this policy may be subject to legal action. Please read Terms Of Use and Privacy Statement for more information. Development by Tore Nestenius at .NET Consultant - Synchron Data.