C和C++11的std::assert

C语音的static_assert:

C和C++11的std::assert_第1张图片

C和C++11的std::assert_第2张图片

C++11的static_assert:

C和C++11的std::assert_第3张图片

示例代码:

#include 
 
template 
void swap(T& a, T& b)
{
    static_assert(std::is_copy_constructible::value,
                  "Swap requires copying");
    static_assert(std::is_nothrow_copy_constructible::value
               && std::is_nothrow_copy_assignable::value,
                  "Swap requires nothrow copy/assign");
    auto c = b;
    b = a;
    a = c;
}
 
template 
struct data_structure
{
    static_assert(std::is_default_constructible::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 ds_ok;
    data_structure ds_error; // 2
}

运行结果:

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

reference:

https://zh.cppreference.com/w/c/error/static_assert

https://zh.cppreference.com/w/c/language/_Static_assert

https://zh.cppreference.com/w/cpp/language/static_asser

你可能感兴趣的:(CPP)