Hey everyone
I was looking at a game engine to see how the different developers structure the code in their projects. I came across this algorithm but cannot figure out what it does exactly.
This algorithm is stored in a header file.
// Static compile-time assertion
namespace StaticAssert
{
template< bool > struct FAILED;
template<> struct FAILED< true > { };
}
#define ASSERT_STATIC( exp ) (StaticAssert::FAILED< (exp) != 0 >())
Can anyone explain what it does? "ASSERT_STATIC" is implemented in a cpp file. Here's the code:
// Check some platform-dependent assumptions
// Note: this function is never called but just wraps the compile time asserts
static void __ValidatePlatform__()
{
ASSERT_STATIC( sizeof( int64 ) == 8 );
ASSERT_STATIC( sizeof( int ) == 4 );
ASSERT_STATIC( sizeof( short ) == 2 );
ASSERT_STATIC( sizeof( char ) == 1 );
}
Thank you for reading!
What does this algorithm do?
Started by Coro, Aug 29 2012 05:10 PM
4 replies to this topic
Ad:
#2 Moderators - Reputation: 4632
Posted 29 August 2012 - 05:26 PM
A static assert is the compile-time equivalent to an assert() call in the code; it makes an assumption about the code at that particular point and throws an error if the assumption does not hold. The code you posted uses template code to evaluate expressions at compile time and determine whether some assumptions (in this case, whether an int is 4 bytes for example) are valid, or the compiler will break with an error.
Take the sizeof(int)==4 expression as an example.
Take the sizeof(int)==4 expression as an example.
- The macro will expand to a template of the StaticAssert::FAILED template class, passing the expression as a template parameter.
- The expression will either evaluate to true or false depending on whether an int really is 4 bytes or not. Thus, the macro and template expands to StaticAssert::FAILED<true>() if the expression is true.
- The extra set of parentheses after the template class name instantiates an instance of the class.
- The actual template class itself is only forward declared: template<bool> struct FAILED, and is then specialized with a complete definition only when the boolean template parameter is true.
#5 Moderators - Reputation: 13458
Posted 29 August 2012 - 09:28 PM
FTFY. A lot of game platforms don't support C++11 yet, so it's common to emulate these features via C++03 code.For the record, it's a non-standard implementation of what the static_assert that's a part of the C++11 language does, only omitting the useful diagnostic message.






