Better HN
topnewbestaskshowjobs
Log inSign up

souperhanz

3 karma · joined Feb 27, 2015 (11y ago) · 2 submissions

Submissions

comment 10y ago · link · parent

It's a very good day. I get to just say "exactly" again. :)

comment 10y ago · link · parent

Exactly. I imagine it's something like the following:

  #include <iostream>
  #include <string>
  #include <utility>
  namespace sp {
    template <typename T>
    struct option {
      template <typename U>
      option(U&& u) : mValue(std::forward<U>(u)) {}
      const T& getValue() const { return mValue; }
      private:
      T mValue;
    };
    struct shell : option<bool> { using option<bool>::option; };
    struct output : option<std::string> { using option<std::string>::option; };
    struct options {
      bool mShell;
      std::string mOutput;
    };
    void applyOpt(options& opts, const shell& opt)
    {
      opts.mShell = opt.getValue();
      std::cout << "shell=" << (opts.mShell ? "true" : "false") << '\n';
    }
    void applyOpt(options& opts, const output& opt)
    {
      opts.mOutput = opt.getValue();
      std::cout << "output=" << opts.mOutput << '\n';
    }
    void applyOpts(options&) {}
    template <typename HeadOpt, typename... TailOpts> void applyOpts(options& opts, HeadOpt&& headOpt, TailOpts&&... tailOpts)
    {
      applyOpt(opts, std::forward<HeadOpt>(headOpt));
      applyOpts(opts, std::forward<TailOpts>(tailOpts)...);
    }
    template <typename... Opts> int call(std::initializer_list<const char*> args, Opts&&... opts)
    {
      std::cout << "args=";
      const char* sep = "";
      for (auto&& s : args)
      {
        std::cout << sep << s;
        sep = " ";
      }
      std::cout << '\n';
      options options;
      applyOpts(options, std::forward<Opts>(opts)...);
      return 0;
    }
  }
  int main()
  {
    sp::call({"ls", "-l"}, sp::shell{true}, sp::output{"foo.txt"});
    return 0;
  }