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

C++ - storing operator as char

本文关键字:char 存储 运算符 C++      更新时间:2023-10-16

我知道这很奇怪,但像下面这样的事情能以某种方式实现吗?

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);
}

当然,这很容易。。。

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);
}

不是这样的。

您需要解析该字符串,然后根据结果切换到相关代码。

您还可以考虑编写一系列函数:

int add(int x, int y) { return x+y; }
int sub(int x, int y) { return x-y; }
// etc.

和typedef:

typedef int (*func)(int,int);

然后创建一个std::map<std::string,func>,这将使查找和调用相关函数的过程非常容易。