Skip to content

Commit 33456be

Browse files
authored
Modernising Tag-Dispatch template with C++17 constexpr if for LinearRegression (lballabio#2198)
2 parents 6092974 + 72a79a8 commit 33456be

File tree

1 file changed

+11
-28
lines changed

1 file changed

+11
-28
lines changed

ql/math/linearleastsquaresregression.hpp

Lines changed: 11 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -48,44 +48,29 @@ namespace QuantLib {
4848
const Size i_;
4949
};
5050

51-
// 1d implementation (arithmetic types)
52-
template <class xContainer, bool>
51+
template <class xContainer>
5352
class LinearFcts {
5453
public:
5554
typedef typename xContainer::value_type ArgumentType;
56-
LinearFcts (const xContainer &x, Real intercept) {
55+
LinearFcts(const xContainer &x, Real intercept) {
5756
if (intercept != 0.0)
58-
v.push_back([=](ArgumentType x){ return intercept; });
59-
v.push_back([](ArgumentType x){ return x; });
57+
v.push_back([=](ArgumentType){ return intercept; });
58+
if constexpr (std::is_arithmetic_v<ArgumentType>) {
59+
v.push_back([](ArgumentType x){ return x; });
60+
} else {
61+
Size m = x.begin()->size();
62+
for (Size i = 0; i < m; ++i)
63+
v.push_back(LinearFct<ArgumentType>(i));
64+
}
6065
}
6166

6267
const std::vector< std::function<Real(ArgumentType)> > & fcts() {
6368
return v;
6469
}
65-
6670
private:
6771
std::vector< std::function<Real(ArgumentType)> > v;
6872
};
6973

70-
// multi-dimensional implementation (container types)
71-
template <class xContainer>
72-
class LinearFcts<xContainer, false> {
73-
public:
74-
typedef typename xContainer::value_type ArgumentType;
75-
LinearFcts (const xContainer &x, Real intercept) {
76-
if (intercept != 0.0)
77-
v.push_back([=](ArgumentType x){ return intercept; });
78-
Size m = x.begin()->size();
79-
for (Size i = 0; i < m; ++i)
80-
v.push_back(LinearFct<ArgumentType>(i));
81-
}
82-
83-
const std::vector< std::function<Real(ArgumentType)> > & fcts() {
84-
return v;
85-
}
86-
private:
87-
std::vector< std::function<Real(ArgumentType)> > v;
88-
};
8974
}
9075

9176
class LinearRegression : public GeneralLinearLeastSquares {
@@ -105,9 +90,7 @@ namespace QuantLib {
10590
LinearRegression::LinearRegression(const xContainer& x,
10691
const yContainer& y, Real intercept)
10792
: GeneralLinearLeastSquares(x, y,
108-
details::LinearFcts<xContainer,
109-
std::is_arithmetic<typename xContainer::value_type>::value>
110-
(x, intercept).fcts()) {
93+
details::LinearFcts<xContainer>(x, intercept).fcts()) {
11194
}
11295

11396
template <class xContainer, class yContainer, class vContainer> inline

0 commit comments

Comments
 (0)