Extract some command line args before passing remainder to legacy code

前端 未结 2 748
长发绾君心
长发绾君心 2021-01-25 08:39

How can one write code so as to fill in the first ellipsis below, so that the legacy code can be given a reduced argument list?:

int main(int argc, char **argv)
         


        
相关标签:
2条回答
  • 2021-01-25 09:15

    The simplest way I can think of is to make a copy of the argument list, filtering out the arguments that the legacy object should not have.

    Something like the following pseudo code:

    new_argc = 0;
    new_argv = new char*[argc];
    for (each argument in argc)
    {
        if (should the argument be copied)
            new_argv[new_argc++] = argv[current_argv_index];
    }
    new_argv[new_argc++] = nullptr;
    
    // ...
    
    LegacyObhect leg(new_argc, new_argv);
    
    // ...
    
    0 讨论(0)
  • 2021-01-25 09:42

    You can try something like this

    int main(int argc, char **argv)
    {
      std::vector<char*> legArgv;
      for(int i = 0; i < argc; ++i) {
          // extract 1 or more optional arguments
          if(isOptional(argv[i])) {
           // ...
          }
          else {
              legArgv.push_back(argv[i]);
          }
      }
      legArgv.push_back(nullptr); // terminate argument vector
    
      // forward remaining
      LegacyObject leg(legArgv.size(), &(legArgv[0])); 
    }
    
    0 讨论(0)
提交回复
热议问题