mardi 18 décembre 2018

To build a constexpr operation hash map

I am dealing with an expression evaluation problem. There are some binary operator, defined as below:

enum Operator {
    add, sub, mul, div, openParenthesis, closeParenthesis, empty
};

(I didn't declare the Operator as an enum class, since it might be use as array index in some cases).

When processing the expression, a function doBinaryOperate is defined as below, it take the operator and operand as input, should return a result.

int doBinaryOperate(int lhs, Operator op, int rhs)
{
    // do something...
}

The operators and their evaluation action's mapping relationship can be determined when coding, so i try to define a constexpr operator map:

constexpr unordered_map<Operator, function<int(int, int)>> binaryOperationMap{
    {Operator::add, [](int lhs, int rhs) {return lhs + rhs;}}
};

and the doBinaryOperate simply translate its work by the map.

However, until C++17, lambdas are not permitted in constant expressions.

I know that i can define the OperationImpl function outside, but are there some other solutions to this question? The OperationImpl are seemed to be only used here.

Aucun commentaire:

Enregistrer un commentaire