Loading [MathJax]/extensions/tex2jax.js
QUGaR 0.0.4
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Concepts
utils.hpp
Go to the documentation of this file.
1#ifndef QUGAR_LIBRARY_UTILS_HPP
2#define QUGAR_LIBRARY_UTILS_HPP
3
10
11#include <qugar/types.hpp>
12
13
14#include <cassert>
15#include <cstddef>
16#include <initializer_list>
17#include <span>
18
19namespace qugar {
20
21// narrow_cast(): a searchable way to do narrowing casts of values
22template<class T, class V> constexpr T narrow_cast(V &&val) noexcept
23{
24 return static_cast<T>(std::forward<V>(val));
25}
26
27//
28// at() - Bounds-checked way of accessing builtin arrays, std::array, std::vector
29//
30template<class T, std::size_t N>
31// NOLINTNEXTLINE (cppcoreguidelines-avoid-c-arrays)
32constexpr T &at(T (&arr)[N], const index ind)
33{
34 assert(ind >= 0 && ind < narrow_cast<index>(N));
35 return arr[narrow_cast<std::size_t>(ind)];
36}
37
38template<class Cont> constexpr auto at(Cont &cont, const index ind) -> decltype(cont[cont.size()])
39{
40 assert(ind >= 0 && ind < narrow_cast<index>(cont.size()));
41 using size_type = decltype(cont.size());
42 return cont[narrow_cast<size_type>(ind)];
43}
44
45template<class T> constexpr T at(const std::initializer_list<T> cont, const index ind)
46{
47 assert(ind >= 0 && ind < narrow_cast<index>(cont.size()));
48 return *(cont.begin() + ind);
49}
50
51template<class T, std::size_t extent = std::dynamic_extent>
52constexpr auto at(std::span<T, extent> spn, const index ind) -> decltype(spn[spn.size()])
53{
54 assert(ind >= 0 && ind < narrow_cast<index>(spn.size()));
55 return spn[narrow_cast<std::size_t>(ind)];
56}
57
58}// namespace qugar
59
60#endif// QUGAR_LIBRARY_UTILS_HPP
QUGaR's main namespace.
Definition affine_transf.hpp:28
constexpr T & at(T(&arr)[N], const index ind)
Definition utils.hpp:32
constexpr T narrow_cast(V &&val) noexcept
Definition utils.hpp:22
std::ptrdiff_t index
Definition types.hpp:19
Declaration of types.