forked from AmbaPant/mantid
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Multipliable.h
72 lines (60 loc) · 2.06 KB
/
Multipliable.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
// Mantid Repository : https://github.com/mantidproject/mantid
//
// Copyright © 2016 ISIS Rutherford Appleton Laboratory UKRI,
// NScD Oak Ridge National Laboratory, European Spallation Source,
// Institut Laue - Langevin & CSNS, Institute of High Energy Physics, CAS
// SPDX - License - Identifier: GPL - 3.0 +
#pragma once
#include "MantidHistogramData/DllConfig.h"
#include <algorithm>
#include <functional>
#include <stdexcept>
#include <type_traits>
namespace Mantid {
namespace HistogramData {
namespace detail {
/** Multipliable
This class is an implementation detail of class like HistogramData::Counts and
HistogramData::HistogramY. By inheriting from it, a type becomes multipliable,
i.e., an object can be multiplied with another objects of the same type.
@author Simon Heybrock
@date 2016
*/
template <class T> class Multipliable {
public:
/// Element-wise multiplication of this and other.
T &operator*=(const T &other) & {
auto &derived = static_cast<T &>(*this);
checkLengths(derived, other);
std::transform(derived.cbegin(), derived.cend(), other.begin(), derived.begin(), std::multiplies<double>());
return derived;
}
/// Element-wise division of this and other.
T &operator/=(const T &other) & {
auto &derived = static_cast<T &>(*this);
checkLengths(derived, other);
std::transform(derived.cbegin(), derived.cend(), other.begin(), derived.begin(), std::divides<double>());
return derived;
}
/// Element-wise multiplication of lhs and rhs.
T operator*(T rhs) const {
auto &derived = static_cast<const T &>(*this);
return rhs *= derived;
}
/// Element-wise division of lhs and rhs.
T operator/(const T &rhs) const {
auto &derived = static_cast<const T &>(*this);
T out(derived);
return out /= rhs;
}
protected:
~Multipliable() = default;
private:
void checkLengths(const T &v1, const T &v2) {
if (v1.size() != v2.size())
throw std::runtime_error("Cannot multiply vectors, lengths must match");
}
};
} // namespace detail
} // namespace HistogramData
} // namespace Mantid