SIMD Vectors
Description
boost::safe_numbers::simd::vec<T, N> holds N values of a safe type T and checks a whole vector at a time.
Each operation computes every lane without branching, builds a mask of the lanes where the scalar operation would report an error, and tests that mask once.
A loop over vectors therefore pays one error branch per vector operation instead of one per element.
C26 adds `<simd>` (`std::simd::vec`), but only the standard integer, character, and floating-point types are vectorizable, and its lane operations have no overflow detection. `simd::vec` wraps a vector of the basis type and adds the checks, so it follows the C26 interface closely while keeping every rule of the scalar safe types.
The header is opt-in and is not part of the convenience header <boost/safe_numbers.hpp>:
#include <boost/safe_numbers/simd.hpp>
This release supports the unsigned element types u8, u16, u32, u64, the signed element types i8, i16, i32, i64, the floating point element types f32 and f64, and their policy forms (sat_u32, strict_i64, basic_i32<H>, sat_f32, basic_f64<H>, and so on).
The Semantic Rule
For every policy, lane i of a vector operation equals the scalar operation on lane i.
When the scalar loop over i = 0 … N - 1 would throw or exit, the vector operation throws the same exception type with the same message as the lowest failing lane, and produces no result.
-
throw_exceptionelements throw exactly what the scalar type throws. -
saturateinteger elements clamp every failing lane, branch free. Division and modulo by zero still throwstd::domain_error, as in the scalar types.saturatefloating point elements (sat_f32,sat_f64) are raw IEEE 754 arithmetic with no check at all, as in the scalar types. -
strictelements callstd::exit(EXIT_FAILURE). -
User defined handlers are called once for every failing lane, in lane order, with exactly the arguments the scalar type passes, and their return values become those lanes.
When the error mask has any lane set, the vector replays the scalar operation lane by lane on a cold, out of line path. The exception classification, the messages, and the handler arguments therefore come from the scalar types themselves.
Compound assignment and ++/-- compute the result before storing it, so a vector that throws is left unchanged.
Neither exists for floating point elements, because the scalar f32 and f64 deliberately provide neither.
Backends
| Backend | Selected when | Lane storage |
|---|---|---|
|
The standard library provides |
|
Portable fallback |
Every other C++20 configuration, or whenever |
|
BOOST_SAFE_NUMBERS_HAS_STD_SIMD is defined when the std::simd backend is in use.
Detection uses cpp_lib_simd or libstdc's `__glibcxx_simd`, because libstdc 16 does not define cpp_lib_simd.
Both backends run the same safe number logic, and the interface is identical except for the std::simd::vec conversions listed below.
The default lane count N is implementation defined: one native register on the std::simd backend and 16 bytes worth of lanes on the fallback.
Use an explicit N whenever the layout matters, for example in a data structure or a file format.
The fallback is a correctness first implementation.
With GCC and Clang at -O2 on x86-64 and ARM64, its addition and saturating addition vectorize with a single error branch (none for saturation), while multiplication and 64-bit lanes are partly or entirely scalar, and GCC may call the multiplication kernel out of line.
On the std::simd backend (GCC 16, x86-64, -O2), checked addition, subtraction, and multiplication compile to vector lane operations, one mask extraction, and one branch, with no calls on the path that does not fail.
With AVX-512, GCC 16’s <simd> pads a vector whose lane count is not a power of two with zero lanes, and its / and % may divide those lanes too, which raises SIGFPE.
simd::vec divides lane by lane in exactly that configuration, and uses the vector division everywhere else.
GCC 16’s <simd> also skips the blend in select when one arm is a compile time constant equal to zero, but it tests that with ==, so an arm of -0.0 lanes comes back as +0.0.
The same happens in min, max, clamp, reduce_min, and reduce_max, which select internally.
simd::vec therefore selects floating point lanes by their bit patterns, in unsigned lanes of the same size, which takes the same number of blend instructions.
GCC 16’s <simd> returns 32-byte vectors from internal helpers when AVX is not enabled, which -Wpsabi reports at the end of the translation unit even for plain std::simd code.
Under -Werror, add -Wno-psabi or #pragma GCC diagnostic ignored "-Wpsabi" to translation units that use vectors of 32 bytes or more (including the 64-bit lanes the 32-bit multiplication check widens into).
|
Synopsis
#include <boost/safe_numbers/simd.hpp>
namespace boost::safe_numbers::simd {
template <typename T, int N = /* implementation defined */>
class vec
{
public:
using value_type = T;
using basis_type = typename T::basis_type;
using mask_type = /* std::simd::mask<basis_type, N> or a fallback mask with the same interface */;
static constexpr auto error_policy {T::error_policy};
static constexpr std::integral_constant<int, N> size {};
// Zero in every lane
constexpr vec() noexcept = default;
// Broadcast: only the exact element type
template <typename U> requires std::is_same_v<U, T>
explicit constexpr vec(U x) noexcept;
// Lane i is gen(std::integral_constant<int, i>{}); gen must return exactly T
template <typename G>
explicit constexpr vec(G&& gen);
// Raw lane interop on every backend
explicit constexpr vec(const std::array<basis_type, N>& lanes) noexcept;
explicit constexpr operator std::array<basis_type, N>() const noexcept;
// Only when BOOST_SAFE_NUMBERS_HAS_STD_SIMD is defined
explicit constexpr vec(const std::simd::vec<basis_type, N>& lanes) noexcept;
explicit constexpr operator std::simd::vec<basis_type, N>() const noexcept;
// Lane conversion as the scalar types convert; an out of range lane throws
// std::domain_error whatever the policy
template <typename U>
explicit constexpr vec(const vec<U, N>& other);
// Read only lane access. Precondition: 0 <= i < N
constexpr T operator[](int i) const noexcept;
// Compound assignment for + - * / %, and for unsigned elements & | ^ << >>, with a vec or a T.
// Integer elements only.
template <typename U> constexpr vec& operator+=(const U& rhs);
// ...
// Integer elements only
constexpr vec& operator++();
constexpr vec operator++(int);
constexpr vec& operator--();
constexpr vec operator--(int);
constexpr vec operator+() const noexcept;
};
// Arithmetic: + - * / with the element's error policy, and % for integer elements
// Unsigned elements only: << >> and the bitwise & | ^ ~
// Signed elements only: unary -
// Comparisons: == != < <= > >= return mask_type
// Each binary operator also accepts (vec, T) and (T, vec), which broadcast the element.
// Free function families, as for the scalar types
template <typename T, int N> constexpr vec<T, N> saturating_add(const vec<T, N>&, const vec<T, N>&) noexcept;
template <typename T, int N> constexpr std::pair<vec<T, N>, typename vec<T, N>::mask_type> overflowing_add(const vec<T, N>&, const vec<T, N>&) noexcept;
template <typename T, int N> constexpr std::optional<vec<T, N>> checked_add(const vec<T, N>&, const vec<T, N>&) noexcept;
template <typename T, int N> constexpr vec<T, N> strict_add(const vec<T, N>&, const vec<T, N>&) noexcept;
// ... and likewise for sub, mul, div, mod, and for unsigned elements shl, shr.
// Floating point elements have only overflowing_add, overflowing_sub, overflowing_mul, and overflowing_div.
// Exact results in lanes twice as wide (8, 16, and 32-bit integer lanes)
template <typename T, int N> constexpr auto widening_add(const vec<T, N>&, const vec<T, N>&) noexcept;
template <typename T, int N> constexpr auto widening_mul(const vec<T, N>&, const vec<T, N>&) noexcept;
// Policy chosen at the call site (integer elements)
template <overflow_policy Policy, typename T, int N> constexpr auto add(const vec<T, N>&, const vec<T, N>&);
// ... and likewise sub, mul, div, mod, and for unsigned elements shl, shr
// Lane algorithms: lane i of min, max, and clamp is std::min, std::max, and std::clamp of lane i
template <typename T, int N> constexpr vec<T, N> select(const typename vec<T, N>::mask_type&, const vec<T, N>&, const vec<T, N>&) noexcept;
template <typename T, int N> constexpr vec<T, N> min(const vec<T, N>&, const vec<T, N>&) noexcept;
template <typename T, int N> constexpr vec<T, N> max(const vec<T, N>&, const vec<T, N>&) noexcept;
template <typename T, int N> constexpr vec<T, N> clamp(const vec<T, N>& v, const vec<T, N>& lo, const vec<T, N>& hi) noexcept;
// Reductions: reduce folds left in lane order with the element's operation.
// For floating point elements, reduce_min and reduce_max require that no lane is NaN.
template <typename T, int N, typename BinaryOperation = std::plus<>> constexpr T reduce(const vec<T, N>&, BinaryOperation = {});
template <typename T, int N> constexpr T reduce_min(const vec<T, N>&) noexcept;
template <typename T, int N> constexpr T reduce_max(const vec<T, N>&) noexcept;
// Mask reductions (std::simd's own on the std::simd backend)
using /* ... */::all_of;
using /* ... */::any_of;
using /* ... */::none_of;
using /* ... */::reduce_count;
using /* ... */::reduce_min_index;
using /* ... */::reduce_max_index;
// Loads and stores of exactly the element type
template <typename V, typename R> constexpr V unchecked_load(R&& r) noexcept;
template <typename V, typename It> constexpr V unchecked_load(It first, std::iter_difference_t<It> n) noexcept;
template <typename V, typename R> constexpr V partial_load(R&& r) noexcept;
template <typename V, typename It> constexpr V partial_load(It first, std::iter_difference_t<It> n) noexcept;
template <typename T, int N, typename R> constexpr void unchecked_store(const vec<T, N>&, R&& r) noexcept;
template <typename T, int N, typename It> constexpr void unchecked_store(const vec<T, N>&, It first, std::iter_difference_t<It> n) noexcept;
template <typename T, int N, typename R> constexpr void partial_store(const vec<T, N>&, R&& r) noexcept;
template <typename T, int N, typename It> constexpr void partial_store(const vec<T, N>&, It first, std::iter_difference_t<It> n) noexcept;
} // namespace boost::safe_numbers::simd
Element Types and Mixing
The element type and its error policy are part of the vector type, and mixing follows the scalar rules exactly:
-
Operations take two vectors of the same element type and lane count, or a vector and one value of its element type, which is broadcast.
-
Mixed widths (
vec<u32, 4> + vec<u16, 4>,vec<f32, 4> + vec<f64, 4>), mixed signedness (vec<i32, 4> + vec<u32, 4>), mixed policies (vec<u32, 4> + vec<sat_u32, 4>), mixed lane counts (vec<u32, 4> + vec<u32, 8>), and built-in operands (v + 1U) are compile time errors with astatic_assertmessage. -
u128andi128elements are rejected, becausestd::simdhas no 128-bit lanes, and so are the bounded types. -
Unary minus is rejected for unsigned elements, and the bitwise and shift operators for signed elements, as for the scalar types. Floating point elements reject every operation the scalar
f32andf64do not provide, listed under Floating Point Operations. -
The converting constructor converts between widths and policies of one signedness only, and between the policies of one floating point width. The scalar types never convert between signed and unsigned, between
f32andf64, or between integers and floating point, so neither do the vectors.
A mask_type is keyed on the lane size, so a mask from a vector of u64 can not select between vectors of u32 on either backend.
Construction, Loads, and Stores
The loads and stores read and write contiguous ranges of exactly the element type (std::array, std::vector, std::span, built-in arrays), or an iterator and a count.
Lanes are copied through each element’s conversion to its basis type, so there is no reinterpret_cast and the copies compile to vector loads and stores.
-
unchecked_loadandunchecked_storerequire at leastNelements; a range with a static extent shorter thanNis a compile time error. -
partial_loadreadsmin(size, N)elements and zero fills the remaining lanes;partial_storewritesmin(size, N)lanes.
Built-in data moves through the raw lane conversions, vec(const std::array<basis_type, N>&) and operator std::array<basis_type, N>(), which never check anything because every basis value is a valid lane.
Unsigned Operations
| Operation | Error lanes | Error under throw_exception |
|---|---|---|
|
The sum wraps |
|
|
The difference would be negative |
|
|
The product exceeds the maximum |
|
|
The divisor is zero |
|
|
|
|
|
|
|
|
Never |
None |
Every lane computation is free of undefined behavior.
Lanes narrower than int multiply in lanes of twice their width, because u16 * u16 promotes to a signed int in which 65535 * 65535 overflows.
Shift counts are sanitized before shifting, and a zero divisor lane takes the error path before any lane is divided.
The 64-bit multiplication has no 128-bit lane to widen into, so it splits each operand into 32-bit halves held in 64-bit lanes.
The product overflows exactly when both high halves are nonzero, when the cross term ah * bl + al * bh reaches 2^32, or when adding the shifted cross term to al * bl carries out.
Every operation stays in vector lanes on every target, so the speed of each one follows the vector instructions of the target and the standard library.
The overflowing_* functions return the wrapped lanes and the error mask, and checked_* return std::nullopt when any lane fails.
Division and modulo still throw std::domain_error on a zero divisor in the saturating_* and overflowing_* families, exactly as the scalar functions do.
Signed Operations
| Operation | Error lanes | Error under throw_exception |
|---|---|---|
|
The exact result is above the maximum, or below the minimum |
|
|
The divisor is zero |
|
|
|
|
unary |
|
|
saturate elements clamp toward the side the exact result left the range on: to the maximum or the minimum for +, -, and *, to the maximum for min / -1 and -min, and to 0, the mathematical result, for min % -1.
A user defined handler receives exactly the scalar arguments, including error_kind::overflow for -min, where throw_exception reports std::domain_error.
Signed lane arithmetic would be undefined behavior on overflow, so every lane computation avoids it:
-
Addition, subtraction, negation,
++, and--run in the unsigned lanes of the same width, where they wrap, and convert back. The overflow test is the sign test of the scalar types: an addition overflows when the operands share a sign that the result does not. -
Lanes of 8, 16, and 32 bits multiply exactly in signed lanes of twice their width and compare the product with the limits.
-
64-bit lanes multiply the magnitudes with the unsigned 32-bit split. The magnitude of a positive product may reach
2^63 - 1and that of a negative product2^63, somin * 1fits andmin * -1does not. -
Before any lane is divided, a zero divisor takes the error path, and the
min / -1lanes divide by 1 instead (min / 1isminandmin % 1is 0, which are the wrapped valuesoverflowing_divandoverflowing_modreturn).
The saturating_*, overflowing_*, checked_*, and strict_* families cover add, sub, mul, div, and mod, as for the scalar signed types; there are no shift functions.
overflowing_div and overflowing_mod flag the min / -1 lanes, and widening_add and widening_mul return lanes of i16, i32, or i64.
Floating Point Operations
| Operation | Error lanes | Error under throw_exception |
|---|---|---|
|
The result is |
|
|
The result is |
|
|
The result is NaN: a NaN operand, or an invalid operation such as |
|
|
A finite nonzero dividend divided by zero |
|
The scalar f32 and f64 report an error exactly when the IEEE 754 result is not finite, and classify the cause only to choose the exception and message.
The vector computes every lane with the IEEE 754 operation, which is never undefined behavior, and its error mask is the lanes outside [lowest, max]: one pair of comparisons that is false for both infinities and for NaN.
When any lane is set, the scalar operator replays the lanes in order, so the lowest failing lane classifies the error exactly as the scalar type does, and a user defined handler receives the scalar arguments (error_kind::overflow, underflow, nan_operation, invalid_operation, or divide_by_zero, with the raw IEEE 754 result) for every failing lane.
sat_f32 and sat_f64 lanes are raw IEEE 754 arithmetic: they never compute a mask, never throw, and their operators are noexcept.
overflowing_add, overflowing_sub, overflowing_mul, and overflowing_div return the raw lanes and the mask of the lanes the operator would have reported, for every policy, and are the only free function family, as for the scalar types.
The surface mirrors the scalar types exactly.
There is no %, compound assignment, +`, `--`, unary ` or -, bitwise or shift operator, and no saturating_*, checked_*, strict_*, widening_*, or generic add<Policy> family, and each of the operators is a static_assert with a message.
There is also no strict_f32, because strict is an integer policy.
Comparisons are IEEE 754 comparisons: a NaN lane compares unequal to everything, and -0.0 equals +0.0.
Lane i of min, max, and clamp is std::min, std::max, and std::clamp of lane i, so ties and NaN lanes resolve as they do for the scalar types: min(a, b) and max(a, b) return a when the lanes are unordered or equal (for example -0.0 and +0.0), and clamp leaves a NaN lane NaN.
GCC 16’s std::simd::min returns b in those lanes, so these are not forwarded to it.
reduce_min and reduce_max require that no lane is NaN, and when both zeros are the extreme value, which of them is returned is unspecified.
Conversions between the policies of one width (vec<f32, N> to vec<sat_f32, N> and back) copy every lane unchanged, including infinities and NaNs, as sat_f32{static_cast<float>(x)} does for a scalar.
On x87 targets (FLT_EVAL_METHOD 2, such as 32-bit x86 without SSE2 math), values pass through 80-bit registers.
Copying a signaling NaN through them quiets it, so a failing lane may report Operation with NAN where the scalar operation on the original value reports Invalid operation (both are std::domain_error).
With GCC’s -fexcess-precision=fast, the scalar types classify the unrounded 80-bit result, so a result just beyond max that rounds to max may throw for the scalar types but not for the vector lanes, which are rounded before they are checked.
|
Deferred Checking
The overflowing_* functions never branch on the error, so a loop can accumulate the masks and test them once at the end:
auto errors {vec4::mask_type{false}};
for (/* each step */)
{
const auto [next, overflowed] {simd::overflowing_add(sum, values)};
sum = next;
errors = errors || overflowed;
}
if (any_of(errors))
{
// handle the overflow once
}
Example
// Copyright 2026 Matt Borland
// Distributed under the Boost Software License, Version 1.0.
// https://www.boost.org/LICENSE_1_0.txt
#include <boost/safe_numbers/simd.hpp>
#include <boost/safe_numbers/iostream.hpp>
#include <array>
#include <iostream>
#include <stdexcept>
int main()
{
using namespace boost::safe_numbers;
using vec4 = simd::vec<u32, 4>;
// Lanes load from a contiguous range of exactly the element type
const std::array<u32, 4> prices {u32{100U}, u32{250U}, u32{3'000'000'000U}, u32{7U}};
const std::array<u32, 4> counts {u32{3U}, u32{2U}, u32{2U}, u32{10U}};
const auto p {simd::unchecked_load<vec4>(prices)};
const auto c {simd::unchecked_load<vec4>(counts)};
// One check covers every lane: lane 2 overflows, so the whole multiplication
// throws exactly what the scalar u32 operation throws
try
{
const auto totals {p * c};
static_cast<void>(totals);
}
catch (const std::overflow_error& e)
{
std::cout << "Error: " << e.what() << '\n';
}
// overflowing_mul returns the wrapped lanes and a mask of the lanes that overflowed
const auto [wrapped, overflowed] {simd::overflowing_mul(p, c)};
for (int i {}; i < vec4::size(); ++i)
{
std::cout << "lane " << i << ": " << wrapped[i] << (overflowed[i] ? " (overflowed)" : "") << '\n';
}
// The error policy comes from the element type: sat_u32 lanes clamp instead
using sat_vec4 = simd::vec<sat_u32, 4>;
const auto clamped {sat_vec4{p} * sat_vec4{c}};
std::cout << "saturated lane 2: " << clamped[2] << '\n';
// Deferred checking: accumulate the masks and test once at the end
auto sum {vec4{}};
auto errors {vec4::mask_type{false}};
for (int step {}; step < 3; ++step)
{
const auto [next, carry] {simd::overflowing_add(sum, p)};
sum = next;
errors = errors || carry;
}
std::cout << "lanes that overflowed while summing: " << reduce_count(errors) << '\n';
// Elementwise operations without errors store straight back to safe values
std::array<u32, 4> out {};
simd::unchecked_store(simd::min(p, c * u32{50U}), out);
std::cout << "min(p, 50 * c) =";
for (const auto x : out)
{
std::cout << ' ' << x;
}
std::cout << '\n';
return 0;
}
Output:
Error: Overflow detected in u32 multiplication lane 0: 300 lane 1: 500 lane 2: 1705032704 (overflowed) lane 3: 70 saturated lane 2: 4294967295 lanes that overflowed while summing: 1 min(p, 50 * c) = 100 100 100 7
// Copyright 2026 Matt Borland
// Distributed under the Boost Software License, Version 1.0.
// https://www.boost.org/LICENSE_1_0.txt
#include <boost/safe_numbers/simd.hpp>
#include <boost/safe_numbers/iostream.hpp>
#include <array>
#include <cstdint>
#include <iostream>
#include <limits>
#include <stdexcept>
int main()
{
using namespace boost::safe_numbers;
using vec4 = simd::vec<i32, 4>;
// Balances and the changes to apply to them
const std::array<i32, 4> balances {i32{1'000}, i32{-2'147'483'000}, i32{2'000'000'000}, i32{-50}};
const std::array<i32, 4> changes {i32{-250}, i32{-1'000}, i32{500'000'000}, i32{75}};
const auto b {simd::unchecked_load<vec4>(balances)};
const auto c {simd::unchecked_load<vec4>(changes)};
// Lane 1 underflows and lane 2 overflows. The lowest failing lane decides what is
// thrown, exactly as a scalar loop over the lanes would.
try
{
const auto totals {b + c};
static_cast<void>(totals);
}
catch (const std::underflow_error& e)
{
std::cout << "Error: " << e.what() << '\n';
}
// overflowing_add returns the wrapped lanes and a mask of the lanes that failed
const auto [wrapped, failed] {simd::overflowing_add(b, c)};
for (int i {}; i < vec4::size(); ++i)
{
std::cout << "lane " << i << ": " << wrapped[i] << (failed[i] ? " (out of range)" : "") << '\n';
}
// sat_i32 lanes clamp toward the side the result left the range on
using sat_vec4 = simd::vec<sat_i32, 4>;
const auto clamped {sat_vec4{b} + sat_vec4{c}};
std::cout << "saturated:";
for (int i {}; i < sat_vec4::size(); ++i)
{
std::cout << ' ' << clamped[i];
}
std::cout << '\n';
// Negation and division are checked too: -min and min / -1 do not fit
const vec4 lowest {i32{std::numeric_limits<std::int32_t>::min()}};
try
{
const auto negated {-lowest};
static_cast<void>(negated);
}
catch (const std::domain_error& e)
{
std::cout << "Error: " << e.what() << '\n';
}
const auto [quotients, overflowed] {simd::overflowing_div(lowest, vec4{i32{-1}})};
std::cout << "lanes where min / -1 overflowed: " << reduce_count(overflowed)
<< " (wrapped quotient " << quotients[0] << ")\n";
// As for the scalar signed types, bitwise and shift operators do not compile:
// b & c; // static_assert: Bitwise AND is deliberately disabled for signed safe integers
return 0;
}
Output:
Error: Underflow detected in i32 addition lane 0: 750 lane 1: 2147483296 (out of range) lane 2: -1794967296 (out of range) lane 3: 25 saturated: 750 -2147483648 2147483647 25 Error: Overflow in i32 unary minus operator lanes where min / -1 overflowed: 4 (wrapped quotient -2147483648)
f32 reports it, together with the overflowing form, raw IEEE 754 sat_f32 lanes, and the lane algorithms.// Copyright 2026 Matt Borland
// Distributed under the Boost Software License, Version 1.0.
// https://www.boost.org/LICENSE_1_0.txt
#include <boost/safe_numbers/simd.hpp>
#include <boost/safe_numbers/iostream.hpp>
#include <array>
#include <iostream>
#include <stdexcept>
int main()
{
using namespace boost::safe_numbers;
using vec4 = simd::vec<f32, 4>;
// Sensor readings and the gains to apply to them
const std::array<f32, 4> readings {f32{1.5f}, f32{-2.25f}, f32{3.0e38f}, f32{8.0f}};
const std::array<f32, 4> gains {f32{2.0f}, f32{4.0f}, f32{10.0f}, f32{0.5f}};
const auto r {simd::unchecked_load<vec4>(readings)};
const auto g {simd::unchecked_load<vec4>(gains)};
// Lane 2 overflows to infinity, so the vector throws exactly what the scalar f32 throws
try
{
const auto scaled {r * g};
static_cast<void>(scaled);
}
catch (const std::overflow_error& e)
{
std::cout << "Error: " << e.what() << '\n';
}
// overflowing_mul returns the raw IEEE 754 lanes and a mask of the lanes that are not finite
const auto [raw, failed] {simd::overflowing_mul(r, g)};
for (int i {}; i < vec4::size(); ++i)
{
std::cout << "lane " << i << ": " << raw[i] << (failed[i] ? " (not finite)" : "") << '\n';
}
// Division by a zero lane is reported as such, as for the scalar types
const vec4 divisors {[](const auto i) { return f32{static_cast<float>(static_cast<int>(i))}; }};
try
{
const auto quotients {r / divisors};
static_cast<void>(quotients);
}
catch (const std::domain_error& e)
{
std::cout << "Error: " << e.what() << '\n';
}
// sat_f32 lanes are raw IEEE 754 arithmetic: no checks and no exceptions
using sat_vec4 = simd::vec<sat_f32, 4>;
const auto ieee {sat_vec4{r} / sat_vec4{divisors}};
std::cout << "saturated:";
for (int i {}; i < sat_vec4::size(); ++i)
{
std::cout << ' ' << ieee[i];
}
std::cout << '\n';
// Lane algorithms follow std::min, std::max, and std::clamp lane by lane
const auto limited {simd::clamp(r, vec4{f32{-1.0f}}, vec4{f32{1.0f}})};
std::cout << "clamped:";
for (int i {}; i < vec4::size(); ++i)
{
std::cout << ' ' << limited[i];
}
std::cout << "\nlargest reading: " << simd::reduce_max(r) << '\n';
// As for the scalar f32, there is no operator%, compound assignment, or unary minus:
// r % g; // static_assert: There is no operator% for floating point safe types
return 0;
}
Output:
Error: Overflow detected in f32 multiplication lane 0: 3 lane 1: -9 lane 2: inf (not finite) lane 3: 4 Error: Division by zero detected in f32 division saturated: inf -2.25 1.5e+38 2.66667 clamped: 1 -1 1 1 largest reading: 3e+38
Limitations
These are not supported yet:
-
u128andi128elements, sincestd::simdhas no 128-bit lanes. -
Bounded element types.
-
CUDA and SYCL device code, which have no
<simd>. -
The C++20 module.
-
<cmath>and<bit>style functions for vectors (GCC 16 implements neither [simd.math] nor [simd.bit]). -
Formatting and stream I/O for vectors, and debugger pretty printers.
-
Masked loads, stores, and reductions.