seams-core v2.14.0
libyodaLib, the C++ engine of d-SEAMS
Loading...
Searching...
No Matches
index_cast.hpp
Go to the documentation of this file.
1//-----------------------------------------------------------------------------------
2// d-SEAMS - Deferred Structural Elucidation Analysis for Molecular Simulations
3// SPDX-License-Identifier: MIT
4//-----------------------------------------------------------------------------------
5#pragma once
6
7#include <concepts>
8#include <cstddef>
9#include <stdexcept>
10#include <utility>
11
12namespace seams {
13
14// Integer conversion for a value that must fit the target type: an index
15// or count that cannot be negative, or a size that must fit an int. A
16// value out of range throws instead of wrapping to a huge index or a
17// negative count. Not for hot loops; those keep their own index type.
18template <std::integral To, std::integral From> constexpr To checkedCast(From value) {
19 if (!std::in_range<To>(value)) {
20 throw std::out_of_range("integer value out of range for its target type");
21 }
22 return static_cast<To>(value);
23}
24
25template <std::integral From> constexpr std::size_t toIndex(From value) {
26 return checkedCast<std::size_t>(value);
27}
28
29} // namespace seams
constexpr std::size_t toIndex(From value)
constexpr To checkedCast(From value)