C++—将运算符存储为char
C++ - storing operator as 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);
}
当然,这很容易。。。
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>
,这将使查找和调用相关函数的过程非常容易。
相关文章:
- 如何在cpp.中使用协议缓冲区存储大缓冲区/数组(char/int)
- 使用 char* 存储数据和产生的错误
- 如何声明一个必须在C++中同时存储int和char值的2D数组
- 如果char可以在C++中存储数字,为什么我们需要int
- C++17:unique_ptr<char[]> 和 shared_ptr<char[] 之间的指针存储差异>
- 将.txt文件存储到 char* 2d 矢量C++中
- 使用 std::vector<char> 作为异构记录的存储是否安全?
- 将 C++ 字符串存储到 char* 向量中
- 哪一个更适合存储字符、矢量<char>或字符串?
- C++ 存储来自 char* 函数的字符列表
- char*中存储的返回int值(0-255)给出了负值
- 将字符指针按顺序存储在 map 中 std::map<char*, int> mymap。将其存储为字符或字符串不是一个选项
- 使用C 中字符串标头的getline()函数将第一个char存储在字符串对象中
- 当您声明指向char数组的指针时,存储在内存中
- 通过无符号 char 别名进行对象访问,加载和存储时会发生什么?
- 在int到char转换期间,int将在char中存储在char中,如果int太大,将在char中存储的值
- C :占用更多内存,将单个字符作为char或字符串存储
- 使用 char*array 存储条形图的条形图,以便我可以动态制作它并作为字符串返回
- 将int转换为十六进制并将其存储到char缓冲区中
- 使用 char* 存储整数