C++ 不添加 `std::vector<std::string>` "overload" 作为 `main()` 的参数的原因是什么?

What is the reason C++ doesn't add `std::vector<std::string>` "overload" as argument to `main()`?

新的 C++17(或更高版本)是否有任何根本原因不允许将 main 写成

的替代方法
int main(std::vector<std::string> args){...}

?我知道需要与以前的代码兼容,所以

int main(int, char**) 

仍然必须存在,但是有什么技术可以阻止第一个 "alternative" 声明吗?

实施起来可能有些困难,至少在一方面是这样。

这基本上需要某种函数重载的反向查找形式。也就是说,启动代码通常大致如下所示:

extern int main(int argc, char *argv[], char *envp[]);

void entry() { 
    // OS-specific stuff to retrieve/parse command line, env, etc.
    static_constructors();
    main(argc, argv, envp);
    execute(onexit_list);
    static_destructors();    
}

根据您的方案,我们需要两段单独的 startup 代码:一段调用 main 传递 argc/argv , 另一个传递一个 std::vector<std::string>.

我应该补充一点,虽然这意味着这项工作并非完全微不足道,但它仍然远非无法克服的问题。仅举一个例子,Microsoft 的 linker 已经 link 了不同的启动代码,具体取决于您是否定义了 mainWinMain(或 wmainwWinMain).因此,显然可以检测用户提供的入口点的(损坏的)名称,并相应地 link 到一组适当的启动代码。

以下是您自己的操作方法,非常简单,只需几行代码:

auto my_main( std::vector<std::string> const& args ) -> int;

auto main( int n_args, char** args )
    -> int
{ return my_main( std::vector<std::string>( args, args + n_args ) ); }

模数表示法我相信这种方法在 Accelerated C++ 书中有介绍,也就是说它是众所周知的。

标准中不用加,觉得有用的直接复制粘贴代码即可。

其他人可能觉得它没用:它在 Windows 中效果不佳,因为按照惯例 main 参数在 Windows 中不是 Unicode,而 Microsoft 的 setlocale 明确不支持 UTF-8 语言环境。