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:
sizeof(T)
(e.g., 32-bit int)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.