Every programmer must know about assert. Those who don’t know assert (or similar) mechanism, they’re not a real programmers
it’s one of the most important helper for debugging. The assert library is designed to work in run time. The expression will be evaluated on program execution and test for sanity. If the express return false, then assert message will be popped up.
What if we can catch the some of the data size or some other constant constraints during compile time itself? it will reduce the overhead of bugs and assertions at run time. e.g In windows, it’s a thumb of rule that user defined messages should be defined greater than WM_USER. What if we can check a class is empty or not at compile-time itself? or the array size exceeds than a limited value?
One of the real example I can tell you from my experience is the stack size issue. By default, thread’s stack size is 1MB. I was using a big structure. it had multiple structures, array of big structures to hold the data. In fact I was using only few elements of this structure and I never taken care of the size of structure. Whenever I enter the function which declared the object of this structure crashes. I could not figure out the reason first time as the structure declaration was at the middle of the function. In this kind of situation I thought, it would be nice if compiler warns us about the structure size. But in my understanding compiler has limitation over these kind of application parameters. But those who are so much cared about this kind of situation can make use of static assert.
As many of you know, most of the C++ 0x standard specification was directly taken or got inspired by boost library. You can see a bunch of examples and demonstration of these features in the boost library as well.
See the code snippet below
// StaticAssert.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iosfwd>
#include <type_traits>
const int WM_USER = 1024;
const int MY_CUSTOM_MESSAGE = 1; // invalid value
class EmptyClass
{
};
class CPoint
{
int x;
int y;
CPoint() { x = y = 0; }
};
struct BigStruct
{
char Dummy[4194304];
};
int _tmain(int argc, _TCHAR* argv[])
{
static_assert( MY_CUSTOM_MESSAGE > WM_USER , "Custom message should be defined greater than WM_USER" );
static_assert( std::tr1::is_pod<CPoint>::value, "This is not a plane old data type" );
static_assert( !std::tr1::is_empty<EmptyClass>::value, "The class should not be empty" );
static_assert( sizeof( BigStruct ) < 1024*1024, "The structure size exceeds stack size" );
return 0;
}