Static Assertion

Performs compile-time assertion checking.

Syntax

static_assert ( bool_constexpr , message ) (since C++11)
static_assert ( bool_constexpr ) (since C++17)

Explanation

bool_constexpr - a constant expression that is contextually convertible to bool
message - optional (since C++17)string literal that will appear as compiler error if bool_constexpr is false

A static assert declaration may appear at block scope (as a block declaration) and inside a class body (as a member declaration).

If bool_constexpr returns true, this declaration has no effect. Otherwise a compile-time error is issued, and the text of message, if any, is included in the diagnostic message.

Note

Since message has to be a string literal, it cannot contain dynamic information or even a constant expression that is not a string literal itself. In particular, it cannot contain the name of the template type argument.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <type_traits>
  
template <class T>
void swap(T& a, T& b)
{
    static_assert(std::is_copy_constructible<T>::value,
                  "Swap requires copying");
    static_assert(std::is_nothrow_move_constructible<T>::value
               && std::is_nothrow_move_assignable<T>::value,
                  "Swap may throw");
    auto c = b;
    b = a;
    a = c;
}
  
template <class T>
struct data_structure
{
    static_assert(std::is_default_constructible<T>::value,
                  "Data Structure requires default-constructible elements");
};
  
struct no_copy
{
    no_copy ( const no_copy& ) = delete;
    no_copy () = default;
};
  
struct no_default
{
    no_default () = delete;
};
  
int main()
{
    int a, b;
    swap(a, b);
  
    no_copy nc_a, nc_b;
    swap(nc_a, nc_b); // 1
  
    data_structure<int> ds_ok;
    data_structure<no_default> ds_error; // 2
}

Possible output:

1
2
1: error: static assertion failed: Swap requires copying
2: error: static assertion failed: Data Structure requires default-constructible elements

See also

C documentation for static_assert
doc_CPP
2025-01-10 15:47:30
Comments
Leave a Comment

Please login to continue.