DiSMEC++
conversion.h
Go to the documentation of this file.
1 // Copyright (c) 2021, Aalto University, developed by Erik Schultheis
2 // All rights reserved.
3 //
4 // SPDX-License-Identifier: MIT
5 
6 #ifndef DISMEC_SRC_UTILS_CONVERSION_H
7 #define DISMEC_SRC_UTILS_CONVERSION_H
8 
9 #include "throw_error.h"
10 
11 namespace dismec {
13  template<class T>
14  constexpr long to_long(T value) {
15  static_assert(std::is_integral_v<T>, "Can only convert between integral types");
16  // I don't think that the if constexpr would be needed here, strictly speaking,
17  // but handling the unsigned case separately prevent -Wsign-compare complaints.
18  if constexpr(std::is_signed_v<T>) {
19  if (value < std::numeric_limits<long>::max()) {
20  return static_cast<long>(value);
21  }
22  } else {
23  if (value < static_cast<unsigned long>(std::numeric_limits<long>::max())) {
24  return static_cast<long>(value);
25  }
26  }
27  THROW_EXCEPTION(std::range_error, "Value {} cannot be represented as long.", value);
28  }
29 
31  template<class T>
32  constexpr std::ptrdiff_t calc_ssizeof() {
33  return static_cast<std::ptrdiff_t>(sizeof(T));
34  }
35 
37  template<class T>
38  constexpr std::ptrdiff_t ssizeof = calc_ssizeof<T>();
39 
41  template <class C>
42  constexpr auto ssize(const C& c) -> std::common_type_t<std::ptrdiff_t, std::make_signed_t<decltype(c.size())>> {
43  using R = std::common_type_t<std::ptrdiff_t, std::make_signed_t<decltype(c.size())>>;
44  return static_cast<R>(c.size());
45  }
46 }
47 
48 #endif //DISMEC_SRC_UTILS_CONVERSION_H
Main namespace in which all types, classes, and functions are defined.
Definition: app.h:15
constexpr auto ssize(const C &c) -> std::common_type_t< std::ptrdiff_t, std::make_signed_t< decltype(c.size())>>
signed size free function. Taken from https://en.cppreference.com/w/cpp/iterator/size
Definition: conversion.h:42
constexpr long to_long(T value)
Convert the given value to long, throwing an error if the conversion is not possible.
Definition: conversion.h:14
constexpr std::ptrdiff_t ssizeof
Signed size of type T
Definition: conversion.h:38
constexpr std::ptrdiff_t calc_ssizeof()
Gets the sizeof of a type as a signed integer.
Definition: conversion.h:32
#define THROW_EXCEPTION(exception_type,...)
Definition: throw_error.h:16