numerical-collection-cpp 0.10.0
A collection of algorithms in numerical analysis implemented in C++
Loading...
Searching...
No Matches
multiply_safely.h
Go to the documentation of this file.
1/*
2 * Copyright 2023 MusicScience37 (Kenta Kabashima)
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
20#pragma once
21
25
26namespace num_collect::util {
27
36template <base::concepts::integral T>
37[[nodiscard]] constexpr auto multiply_safely(T a, T b) -> T {
38 const T res = a * b;
39 if (a != static_cast<T>(0) && res / a != b) {
41 algorithm_failure, "Overflow in multiplication.");
42 }
43 return res;
44}
45
46} // namespace num_collect::util
Class of exception on failure in algorithm.
Definition exception.h:93
Definition of exceptions.
Definition of integral concept.
Definition of macros for logging.
#define NUM_COLLECT_LOG_AND_THROW(EXCEPTION_TYPE,...)
Write an error log and throw an exception for an error.
Namespace of utilities.
Definition assert.h:30
constexpr auto multiply_safely(T a, T b) -> T
Multiply two integers with check of overflow.