小埋社区

    • Register
    • Login
    • Search
    • Categories
    • Recent
    • Tags
    • Popular
    • Users
    • Groups

    一种优雅地实现C++ string switch的方法

    编程
    c++
    1
    1
    389
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • Bruce
      Bruce ACG last edited by

      #include <unordered_map>
      #include <functional>
      #include <string>
      #include <cstdio>
      
      template <typename T>
      class Switch
      {
      private:
          T expression;
          std::unordered_map<T, std::function<void()>> map;
          std::function<void()> defaultFunction;
      
      public:
          Switch(const T& v) { this->expression = v; }
          Switch& case_(const T& c, const std::function<void()>& f) {
              map[c] = f;
              return *this;
          }
          Switch& default_(const std::function<void()>& f) {
              this->defaultFunction = f;
              return *this;
          }
          virtual ~Switch() {
              if (map[expression]) {
                  map[expression]();
              } else {
                  defaultFunction();
              }
          }
      };
      
      int main(int argc, char* argv[])
      {
          if (argc < 2) {
              return 1;
          }
          std::string v(argv[1]);
      
          Switch<std::string>(v)
              .case_("hello", [] { std::printf("get hello\n"); })
              .case_("world", [] { std::printf("get world\n"); })
              .default_([] { std::printf("get other string\n"); });
      
          Switch<int>(argc)
              .default_([=] { std::printf("get %d args\n", argc); });
      
          return 0;
      }
      
      1 Reply Last reply Reply Quote 0
      • First post
        Last post
      © 2017-2022 小埋社区 All Rights Reserved | 皖ICP备17016228号-2