C ++ / CLI switch to String

In other .NET languages, such as C #, you can include a string value:

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

This is not like C ++ / CLI

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

Is there a special keyword or other way to make this work for C ++ / CLI, as in C #?

+3
source share
4 answers

In fact, you can use anything other than integers (sometimes denoted by integer types) if the test objects determine the conversion to integer.

String object does not work.

However, you can create a map with string keys (check that the comparison is well-processed) and pointers to classes that implement some interface as values:

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

A bit longer to implement, but well designed.

+5

, , , switch C/++. ++ - ... else:

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

Edit:

, ++/CLI - , ; , , ANSI ++.

0

I think I found a solution on codeguru.com .

0
source

I know that my answer comes a little later, but I think this is also a good solution.

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;

 }
}
0
source

Source: https://habr.com/ru/post/1711134/


All Articles