Closed. This question needs details or clarity。它当前不接受答案。
                            
                        
                    
                
                            
                                
                
                        
                            
                        
                    
                        
                            想改善这个问题吗?添加详细信息并通过editing this post阐明问题。
                        
                        5年前关闭。
                                                                                            
                
        
我正在实现一个基本的解释器功能,该功能可模拟“条件跳转”。
它需要四个输入,分别是


变量(字符类型)
运算符( ...)(字符串类型)
整数值(int类型)
行号(int类型)


功能声明

void ProgramState::conditionalJump(int var, std::string op, int immediate, int destination);
// condition: Compares var and immediate using op
// if condition is true: modify current address to destination if the
// if false: nothing happens


例如,我可以编写一个非常粗糙的实现,如下所示:

例:

if ( (op == "<") && (var < immediate) ){
    cur_line = destination;
}


有一个简单的方法吗?
我曾考虑过重载运算符,但不确定它是否有效。

最佳答案

我认为您要问的是如何将std::string转换为relational operator。好吧,我不知道通过元编程来实现这一目标的任何方法,但是字符串类只有6 relational operators。因此,我只是将它们硬编码到函数中。

例:

void conditionalJump(int var, std::string op, int immediate, int destination)
{
   if      ((op == "==") && (var == immediate))  cur_line = destination;
   else if ((op == "!=") && (var != immediate))  cur_line = destination;
   else if ((op == "<")  && (var < immediate))   cur_line = destination;
   else if ((op == ">")  && (var > immediate))   cur_line = destination;
   else if ((op == "<=") && (var <= immediate))  cur_line = destination;
   else if ((op == ">=") && (var >= immediate))  cur_line = destination;
}


如果这不是您想要的,那么我想您可能想签出以下链接:


C++ relational operators generator
Using character as relational operator in C/C++

09-06 11:31