Thursday, December 13, 2012

C++11 Standard Explained: 3. Static Assertion

C++11 comes with a very nice functionality: static assertion.
static_assertion enables programmers to check for things during compilation.
Syntax is :
static_assert--(--constant-expression--,--string-literal-----)
More explanation for the details may be found here:
http://publib.boulder.ibm.com/infocenter/zos/v1r12/index.jsp?topic=%2Fcom.ibm.zos.r12.cbclx01%2Fsadec.htm

I will talk about some useful applications of it.
If you have some code for byte hacking, you may want to check for the size of integer. The following structure will enable you to do that.
I will check if long double is 64 bit in the system

template 
struct CheckSize {
        static_assert(sizeof(int64_t) == sizeof(T), "not big enough");
};
Later, you may check for the size of long long by doing the following:
    CheckSize<long double> check1; The other useful thing I found was that you could check for different system limits during compile time, to make sure that behavior is expected. You may check file pat limit like this:

static_assert(PATH_MAX <= 4096, "type is not size 8");

No comments:

Post a Comment