Extract some command line args before passing rema

2019-02-28 21:47发布

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)
{
  // extract 1 or more optional arguments

  ...

  // forward remaining
  LegacyObject leg(argc_2, argv_2); 

}

2条回答
2楼-- · 2019-02-28 22:08

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])); 
}
查看更多
不美不萌又怎样
3楼-- · 2019-02-28 22:17

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);

// ...
查看更多
登录 后发表回答