TYPE TRAITS AND STATIC ASSERTIONS

A static assertion enables you to detect usage errors at compile time. A static assertion is of the form:

static_assert(constant_expression, string_literal);

The constant_expression should result in a value that is convertible to type bool. If the result is true, the statement does nothing; if it is false, the string literal will be displayed by the compiler. A static assertion has no effect on the compiled code. Note that static_assert is a keyword.

The type_traits header defines a range of templates that enable you to create compile-time constants that you can use in conjunction with static assertions to cause the compiler to issue customized error messages. I don’t have the space to describe the contents of type_traits in detail so I’ll just give you one example and use type traits in the next section.

The type_traits header includes several templates for testing types that are particularly useful when you are defining your own templates. Suppose you define the following template:

template<class T>
T average(const std::vector<T>& data)
{
  T sum(0);
  for(auto& value : data)
    sum += value;
  return sum/data.size();
}

This template is intended to be used with a vector of values that are of an arithmetic type. It would be useful to be able to prevent the template from being used with non-arithmetic types — Person objects, for example. If this can be caught at compile time, it will prevent a runtime crash from occurring. A static_assert in conjunction ...

Get Ivor Horton's Beginning Visual C++ 2012 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.