c++11 - C++ Utility to convert long switch statement into the concise function call which encapsulates the switch case ladder -


i want write c++ utility can following:

current workflow

int num; std::string str; switch(num){     case 2:         str = "two";     break;     case 5:         str = "five";     break;     case 7:         str = "seven";     break; } 

i want achieve this:

//key guaranteed int value can declare_switch( {     {2 , "two"},     {5 , "five"},     {7 , "seven"} })  int num = 5; std::string str;  match(num,str,arr); //here str == "five" 

i want write declare_switch , match functions. there no restriction on language constructs - preprocessor macro, templates do.however, if there simple solution or trick. know associative data structures not want use data structure. question using switch case.

with map can make code similar original sample

#include <map> #include <string> #include <iostream>  int main() {     std::map<int,std::string> declare_switch {         {2 , "two"},         {5 , "five"},         {7 , "seven"}      };      int num = 5;     std::string str = declare_switch[num];      std::cout << str << '\n';     return 0; } 

note operator [] insert new entry map if not present. avoid such behavior have use find

#include <map> #include <string> #include <iostream>  std::string match(int number, const std::map<int,std::string>& declare_switch ) {     auto q = declare_switch.find(number);     if (q==declare_switch.end()) {         return "";     }     else         return q->second; }  int main() {     const std::map<int,std::string> declare_switch {         {2 , "two"},         {5 , "five"},         {7 , "seven"}     }; //now can declare map const      int num = 5;     std::string str = match(num,declare_switch);      std::cout << str << '\n';     return 0; } 

Comments

Popular posts from this blog

python - Operations inside variables -

Generic Map Parameter java -

arrays - What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it? -