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.

template < class T, int Size >
class Vector
{
   static_assert(Size > 3, "Vector size is too small!");

   T m_values[Size];
};

int _tmain(int argc, _TCHAR* argv[])
{
   Vector< int, 4 > four;
   Vector< short, 2 > two;

   return 0;
}

Compiling this program triggers an error at the second declaration.

c:\projects\cpp_demo\cpp_demo.cpp(17) : error C2338: Vector size is too small!
  c:\projects\cpp_demo\cpp_demo.cpp(33) : see reference to class template instantiation 'Vector< T,Size >' 
  being compiled
  with
  [
     T=short,
     Size=2
  ]

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.

static_assert(sizeof(long) >= 8, "64-bit code generation required for this library.");

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).

template < class T >
class foo
{
   static_assert(convertible_from< IListener >(decltype(T)), "Type is not a correct type!");
};

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.