##### cppreference.com

##### Search

Create account

##### Namespaces

- Page
- Discussion

##### Variants

##### Views

- View
- Edit
- History

##### Actions

# Static Assertion

From cppreference.com
< cpp‎ | language

Performs compile-time assertion checking

### [edit] Syntax

`static_assert` `(` bool_constexpr `,` string `)` |  | (since C++11)

### [edit] Explanation

bool_constexpr | - | a constant expression that is contextually convertible to bool
string | - | 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)

### [edit] Example

Run this code

    #include <type_traits>

    template <class T>
    void swap( T& a, T& b)
    {
        static_assert(std::is_copy_constructible<T>::value,
                      "Swap requires copying");

        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: error: static assertion failed: Swap requires copying
    2: error: static assertion failed: Data Structure requires
                                       default-constructible elements

### [edit] See also

- assert
- type traits

Retrieved from "http://en.cppreference.com/mwiki/index.php?title=cpp/language/static_assert&oldid=67171"