C++ Logo

std-proposals

Advanced search

Re: [std-proposals] D3803R0 More standard forms of main

From: (wrong string) Åberg <haberg_1_at_[hidden]>
Date: Thu, 24 Jul 2025 09:32:14 +0200
> On 22 Jul 2025, at 12:40, Jan Schultke via Std-Proposals <std-proposals_at_[hidden]> wrote:

> I'm cooking up a draft for a proposal:
> https://gist.github.com/Eisenwave/78d6127b73c6c9a1bc4cb55ad7bf249c
>
> In short, the goal is for "int main(int, const char**)" and some other
> signatures to be permitted.

> Let me know what you think :)

A general form is
  template<class Arg, class Env>
  int main(Arg args, Env envs);
where Arg, Env are types T with constructors of the form
  T(char** first, char** last)

The implementation then performs, relative to
  int main(int argc, char* argv[], char* envp[]);
 the equivalent of
    Arg args(argv, argv + argc);

    size_t envc = 0;

    for (char** p = envp; *p != nullptr; ++p)
      ++envc;

    Env env(envp, envp + envc);

This picks up the environment strings. If one wants to have the parts split up in an associative container Assoc, some more work needs to be done:
    Assoc envs;

    for (auto& i: env) {
      auto k = i.find('=');

       // If the '=' is missing, the string is illegal and ignored.
       if (k != i.npos)
        envs.emplace(i.substr(0, k), i.substr(k + 1));;
    }

Here is an example implementation:
int main(int argc, char* argv[], char* envp[])
{
  std::vector<std::string> args(argv, argv + argc);

  size_t envc = 0;

  for (char** p = envp; *p != nullptr; ++p)
    ++envc;

  std::vector<std::string> env(envp, envp + envc);


  std::map<std::string, std::string> envs;

  for (auto& i: env) {
    auto k = i.find('=');

    // If the '=' is missing, the string is illegal and ignored.
    if (k != i.npos)
      envs.emplace(i.substr(0, k), i.substr(k + 1));;
  }

  for (auto& i: args)
    std::cout << i << std::endl;

  for (auto& i: env)
    std::cout << i << std::endl;

  for (auto i: envs)
    std::cout << i.first << "=" << i.second << std::endl;
}

Received on 2025-07-24 07:32:34