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

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -