RAD Studio |  |

Static Assertions (C++0x)
Syntax | See Also
Collapse All

The static_assert keyword is used to test assertions at compile time. This is one of the C++0x features added to C++Builder 2009.

This keyword operates differently than the macro assert, which raises assertions at run time. The keyword static_assert also differs from the preprocessor directive #error, which operates during preprocessing and simply emits a message.

Syntax

A static assertion's declaration is:

Copy Code

    static_assert (constant-expression, error-message);

The constant-expression must be one that can be statically evaluated as a boolean. If constant-expression is true, the statement does nothing. If false, the compiler generates an error with the text error-message. Because the assertion is tested at compile time, static_assert can do error checking in templates. For instance:

Copy Code

    template <class T>
       T Test(T x, T y) {
       static_assert(sizeof T <= sizeof long, "Type is too large");
       ...
       };

static_assert is useful for static type checking. A certain function might fail if the implementation of an int is too small, so static_assert has utility outside of templates.

See Also

C++0x Features (C++Builder 2009)

Working Draft - Standard for Programming Language C++ (Sec. 7.1 - Specifiers)

Copyright(C) 2009 Embarcadero Technologies, Inc. All Rights Reserved.
What do you think about this topic? Send feedback!