static assert

suggest change

Assertations mean that a condition should be checked and if it’s false, it’s an error. For static_assert(), this is done compile-time.

template<typename T>
T mul10(const T t)
{
    static_assert( std::is_integral<T>::value, "mul10() only works for integral types" );
    return (t << 3) + (t << 1);
}

A static_assert() has a mandatory first parameter, the condition, that is a bool constexpr. It might have a second parameter, the message, that is a string literal. From C++17, the second parameter is optional; before that, it’s mandatory.

template<typename T>
T mul10(const T t)
{
    static_assert(std::is_integral<T>::value);
    return (t << 3) + (t << 1);
}

It is used when:

Note that static_assert() does not participate in SFINAE: thus, when additional overloads / specializations are possible, one should not use it instead of template metaprogramming techniques (like std::enable_if<>). It might be used in template code when the expected overload / specialization is already found, but further verifications are required. In such cases, it might provide more concrete error message(s) than relying on SFINAE for this.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


static assert:
* static assert

Table Of Contents
8 Arrays
11 Loops
39 Streams
51 Unions
56 Lambdas
60 SFINAE
62 RAII
67 Sorting
84 RTTI
87 Scopes
89 static assert
104 Profiling
107 Recursion
117 Iteration
125 Alignment
134 Semaphore
136 Debugging
139 Mutexes
142 decltype