Está en la página 1de 3

Aserciones estticas (static_assert)

Al igual que C++11, esta nueva versin de C aade una nueva palabra
clave, static_assert, que permite aadir aserciones en el cdigo que
se ejecutan a nivel de compilador.
Las aserciones se encargan de comprobar condiciones que tienen que
cumplirse a la hora de ejecutar una seccin de cdigo. Lo que hace
especiales a estas aserciones es que no se ejecutan en tiempo de
ejecucin (cuando el programa es ejecutado por el usuario), si no que
son comprobaciones realizadas en la fase de compilacin (en una fase
tarda donde los tipos son conocidos).
static_assert(sizeof(void*) >=8, "No eres de 64-bit :P");

Este tipo de aserciones completa a las dos existentes anteriormente.


La que se ejecuta con el preprocesador, #error, y la que se ejecuta en
tiempo de ejecucin, assert().
Syntax
1 static_assert-declaration:
_Static_assert( constant-expression , string-literal ) ;
Constraints
2 The constant expression shall compare unequal to 0.
Semantics
3 The constant expression shall be an integer constant expression. If the
value of the
constant expression compares unequal to 0, the declaration has no effect.
Otherwise, the
constraint is violated and the implementation shall produce a diagnostic
message that
includes the text of the string literal, except that characters not in the basic
source
character set are not required to appear in the message.

Forward references: diagnostics (7.2).

//author: shobhitupadhyaya
template < class T, size_t length >
class String
{
static_assert(length < 100, "length is too big");
T str_data[length];
};
int main()
{
String<int, 101 > a1;
String<int, 90 > a2;
return 0;
}

he above code gives you the following error at compile time,


because in the static_assert we have a condition string length
should be less than 100. But we are trying to give a string length
greater than 100.
error C2338: length is too big
: see reference to class template instantiation 'String<int,101>'
being compiled

The new C++ standard defines a new keyword, static_assert, that is


already available in Visual Studio 2010 CTP. This new feature allows
introducing compile time asserts. It takes an expression that can
evaluate to bool and a string. If the expression evaluates to false, the
compiler issues an error with the given string literal. If the expression
evaluates to true, static_assert has no effect.
Here is an example for using static_assert. Suppose you want to
create a template vector class, but you dont want to allow vectors
with a size smaller than 4. Then you can use a static assertion to
enforce that.

error C2338: length is too big


: see reference to class template instantiation 'String<int,101>'
being compiled

template< class T, int Size >


class Vector
{
static_assert(Size > 3, "Vector size is too small!");
T m_values[Size];
};
int _tmain(intargc, _TCHAR* argv[])
{
Vector<int, 4 > four;
Vector< short, 2 > two;
return 0;
}

También podría gustarte