Static Assertion and Type Trait
Use static assertion and type trait for error check.
1. Static Assertion
static_assert
is a compile-time assertion that checks if a given condition is true.
1 |
|
1 | <source>:6:4: error: static_assert failed due to requirement '16 < 5' "Size is too large" |
2. Type Trait
Type traits provide ways to query and modify types at compile time.
Common Type Traits
Here are some common type traits and their purposes:
Type Information
:
- std::is_integral
: Checks if T is an integral type. - std::is_floating_point
: Checks if T is a floating-point type. - std::is_pointer
: Checks if T is a pointer type. - std::is_array
: Checks if T is an array type.
Type Modifiers
:
- std::remove_cv
: Removes const and volatile qualifiers from T. - std::remove_reference
: Removes reference qualifiers from T. - std::remove_pointer
: Removes pointer qualifiers from T.
Composite Type Traits
:
- std::is_same<T, U>: Checks if T and U are the same type.
- std::is_base_of<Base, Derived>: Checks if Base is a base class of Derived.
- std::is_convertible<From, To>: Checks if From can be implicitly converted to To.
Property Queries
:
- std::is_const
: Checks if T is const-qualified. - std::is_volatile
: Checks if T is volatile-qualified. - std::is_signed
: Checks if T is a signed type. - std::is_unsigned
: Checks if T is an unsigned type.
1 |
|
3. Use them together
Combining static_assert and type traits in C++ allows you to enforce compile-time checks on template parameters or any other types, ensuring that the types meet certain criteria before the code is allowed to compile. This can be very useful for template programming to provide clear and immediate feedback to the developer. If the type or condition is determined at runtime, static_assert
can not be used directly to do such checks.
1 |
|
Static Assertion and Type Trait
http://chuzcjoe.github.io/2024/08/03/cpp-static-assert-type-trait/