File indexing completed on 2024-04-06 12:01:19
0001 #ifndef CommonTools_Utils_formulaBinaryOperatorEvaluator_h
0002 #define CommonTools_Utils_formulaBinaryOperatorEvaluator_h
0003
0004
0005
0006
0007
0008
0009
0010
0011
0012
0013
0014
0015
0016
0017
0018
0019
0020
0021
0022 #include <memory>
0023
0024
0025 #include "formulaEvaluatorBase.h"
0026
0027
0028
0029 namespace reco {
0030 namespace formula {
0031 class BinaryOperatorEvaluatorBase : public EvaluatorBase {
0032 public:
0033 BinaryOperatorEvaluatorBase(std::shared_ptr<EvaluatorBase> iLHS,
0034 std::shared_ptr<EvaluatorBase> iRHS,
0035 Precedence iPrec)
0036 : EvaluatorBase(iPrec), m_lhs(iLHS), m_rhs(iRHS) {}
0037
0038 BinaryOperatorEvaluatorBase(Precedence iPrec) : EvaluatorBase(iPrec) {}
0039
0040 void swapLeftEvaluator(std::shared_ptr<EvaluatorBase>& iNew) { m_lhs.swap(iNew); }
0041
0042 void setLeftEvaluator(std::shared_ptr<EvaluatorBase> iOther) { m_lhs = std::move(iOther); }
0043 void setRightEvaluator(std::shared_ptr<EvaluatorBase> iOther) { m_rhs = std::move(iOther); }
0044
0045 EvaluatorBase const* lhs() const { return m_lhs.get(); }
0046 EvaluatorBase const* rhs() const { return m_rhs.get(); }
0047
0048 private:
0049 std::shared_ptr<EvaluatorBase> m_lhs;
0050 std::shared_ptr<EvaluatorBase> m_rhs;
0051 };
0052
0053 template <typename Op>
0054 class BinaryOperatorEvaluator : public BinaryOperatorEvaluatorBase {
0055 public:
0056 BinaryOperatorEvaluator(std::shared_ptr<EvaluatorBase> iLHS,
0057 std::shared_ptr<EvaluatorBase> iRHS,
0058 Precedence iPrec)
0059 : BinaryOperatorEvaluatorBase(std::move(iLHS), std::move(iRHS), iPrec) {}
0060
0061 BinaryOperatorEvaluator(Precedence iPrec) : BinaryOperatorEvaluatorBase(iPrec) {}
0062
0063
0064 double evaluate(double const* iVariables, double const* iParameters) const final {
0065 return m_operator(lhs()->evaluate(iVariables, iParameters), rhs()->evaluate(iVariables, iParameters));
0066 }
0067
0068 std::vector<std::string> abstractSyntaxTree() const final {
0069 std::vector<std::string> ret;
0070 if (lhs()) {
0071 ret = shiftAST(lhs()->abstractSyntaxTree());
0072 } else {
0073 ret.emplace_back(".nullptr");
0074 }
0075 if (rhs()) {
0076 auto child = shiftAST(rhs()->abstractSyntaxTree());
0077 for (auto& v : child) {
0078 ret.emplace_back(std::move(v));
0079 }
0080 } else {
0081 ret.emplace_back(".nullptr");
0082 }
0083 ret.emplace(ret.begin(), std::string("op ") + std::to_string(precedence()));
0084 return ret;
0085 }
0086
0087 BinaryOperatorEvaluator(const BinaryOperatorEvaluator&) = delete;
0088
0089 const BinaryOperatorEvaluator& operator=(const BinaryOperatorEvaluator&) = delete;
0090
0091 private:
0092
0093 Op m_operator;
0094 };
0095 }
0096 }
0097
0098 #endif