C++ - 将运算符存储为char

coo*_*roc 0 c++ operators char

我知道奇怪的问题,但是可能会以某种方式得到以下内容吗?

int main (int argc, char * const argv[]) 
{
    const char* op1="+";
    int i = 10;
    int j = 20;
    int k = i op1 j; //compiler error, expected , or ; before op1

    printf("k is: %i", k);
}
Run Code Online (Sandbox Code Playgroud)

And*_*zos 6

当然,这很容易......

template <class T>
T execute_operator(T a, string op, T b)
{
    static unordered_map<string, function<T(T,T)>> operators =
    {
        { "+", [](T a, T b) { return a + b; } },
        { "-", [](T a, T b) { return a - b; } },
        etc
    };

    return operators[op](a,b);
};

int main (int argc, char * const argv[]) 
{
    const char* op1="+";
    int i = 10;
    int j = 20;
    int k = execute_operator(i,op1,j);

    printf("k is: %i", k);
}
Run Code Online (Sandbox Code Playgroud)