代码之家  ›  专栏  ›  技术社区  ›  heavyd

字符串上的C++/CLI开关

  •  3
  • heavyd  · 技术社区  · 16 年前

    string val = GetVal();
    switch(val)
    {
    case "val1":
      DoSomething();
      break;
    case "val2":
    default:
      DoSomethingElse();
      break;
    }
    

    在C++/CLI中似乎并非如此

    System::String ^val = GetVal();
    switch(val)  // Compile error
    {
       // Snip
    }
    

    4 回复  |  直到 16 年前
        1
  •  5
  •   dilig0    16 年前

    实际上,如果测试对象定义了整数转换,则可以使用整数以外的任何值(有时由整数类型指定)。

    字符串对象没有。

    class MyInterface {
      public:
        virtual void doit() = 0;
    }
    
    class FirstBehavior : public MyInterface {
      public:
        virtual void doit() {
          // do something
        }
    }
    
    class SecondBehavior : public MyInterface {
      public:
        virtual void doit() {
          // do something else
        }
    }
    
    ...
    map<string,MyInterface*> stringSwitch;
    stringSwitch["val1"] = new FirstBehavior();
    stringSwitch["val2"] = new SecondBehavior();
    ...
    
    // you will have to check that your string is a valid one first...
    stringSwitch[val]->doit();    
    

    实施起来有点长,但设计得很好。

        2
  •  0
  •   DaveR    16 年前

    switch C/C++中的语句。在C++中,最简单的方法就是使用if。..其他声明:

    std::string val = getString();
    if (val.equals("val1") == 0)
    {
      DoSomething();
    }
    else if (val.equals("val2") == 0)
    {
      DoSomethingElse();
    }
    

    编辑:

        3
  •  0
  •   To1ne    16 年前
        4
  •  0
  •   gotch4    16 年前

    struct ltstr {
        bool operator()(const char* s1, const char* s2) const {
            return strcmp(s1, s2) < 0;
        }
    };
    
    std::map<const char*, int, ltstr> msgMap;
    
    enum MSG_NAMES{
     MSG_ONE,
     MSG_TWO,
     MSG_THREE,
     MSG_FOUR
    };
    
    void init(){
    msgMap["MSG_ONE"] = MSG_ONE;
    msgMap["MSG_TWO"] = MSG_TWO;
    }
    
    void processMsg(const char* msg){
     std::map<const char*, int, ltstr>::iterator it = msgMap.find(msg);
     if (it == msgMap.end())
      return; //Or whatever... using find avoids that this message is allocated in the map even if not present...
    
     switch((*it).second){
      case MSG_ONE:
       ...
      break:
    
      case MSG_TWO:
      ...
      break;
    
     }
    }