Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::integral — constraining integer types

std::integral from <concepts> checks at compile time whether a type is integral. It includes bool and character types, preserves its result under const and volatile qualification, but rejects references, enumerations, and floating-point types.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

#include <concepts>

// Definition in namespace std:
template<class T>
concept integral = is_integral_v<T>;

// Usage:
// template<std::integral T> ...
// template<class T> requires std::integral<T> ...

std::integral<T> is a concept from <concepts>, defined as std::is_integral_v<T>. It checks a type category at compile time, not an argument's value: double does not satisfy it even when it holds 4.0.

The concept includes signed and unsigned integer types, as well as bool and character types such as char and wchar_t. Enumeration types and classes do not satisfy it merely because they can convert to int. The qualifiers const and volatile do not change the result: std::integral<const int> is true. References, however, are not integral types, so std::integral<int&> is false.

Use template<std::integral T> to constrain the type argument T; alternatively, write template<class T> requires std::integral<T>. When T is deduced from a by-value parameter, as in the example, an ordinary double argument will not satisfy the constraint. This is a type test, not a general convertibility test.

std::signed_integral and std::unsigned_integral additionally distinguish signedness. Beware: bool satisfies std::unsigned_integral, and the signedness classification of char depends on the implementation. Thus, std::integral alone does not exclude Boolean values or characters; add separate constraints if your algorithm cannot handle them.

Examples

#include <concepts>
#include <iostream>

enum Number { one = 1 };

static_assert(std::integral<int>);
static_assert(std::integral<const volatile int>);
static_assert(std::integral<bool>);
static_assert(std::integral<char>);
static_assert(!std::integral<int&>);
static_assert(!std::integral<double>);
static_assert(!std::integral<Number>);

template<std::integral T>
constexpr bool is_even(T value) {
    return value % 2 == 0;
}

int main() {
    std::cout << std::boolalpha
              << is_even(42) << ' '
              << is_even(7u) << '\n';
}

Result

true false

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources