C++ static_assert, a niche feature

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 don’t want to allow vectors with a size smaller than 4. Then you can use a static assertion to enforce that.

Compiling this program triggers an error at the second declaration.

Most of the use cases for this feature, in my opinion, would be to test on the size of different types. For instance this sample is taken from the C++0x draft.

To me, static_assert looks like a niche feature. It would have been great if this could be used together with some other features to enfore compile time constraints on types. For instance, I want to restrict the possible types for a template class or function to only those that are derived from IListener (a fictive class).

Perhaps a future standard version will offer support for such things.

2 Replies to “C++ static_assert, a niche feature”

  1. The type checking example you wanted is actually possible in vs10 by combining the type_traits provided by tr1 and static_assert

    #include

    template
    class foo
    {
    static_assert( std::is_convertible::value, “Type is not a correct type!” );
    // OR
    static_assert( std::is_base_of::value, “Type is not a correct type!” );
    };

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.