对于具有传递标准库“#include”的 C++ 项目来说,“import std;”是一个现实的目标吗?

swe*_*mer 11 c++ c++-modules

Visual Studio 2022 17.5 及更高版本支持导入 C++23 标准库命名模块std,方法是将 的所有实例替换#include <header>import std;where<header>是标准库头。

根据教程,有一些限制,例如:

不要混合和匹配导入 C++ 标准库头文件和命名模块。例如,不要 #include <vector> 和 import std; 在同一个文件中。

这是否意味着如果我import std;在文件中使用(通过“文件”我假设本教程指的是.cpp文件或其他翻译单元),那么它所包含的任何非标准库头都#include不允许传递到#include标准库标题?

我很确定答案显然是肯定的,因为在预处理之后,是否存在并不重要#include- 它的内容最终将.cpp与语句混合在文件中import

但是,除了彻底搜索所有传递性之外,还可以采取什么措施来防止混合呢?#include但是,除了彻底搜索所有传递性以查看是否存在任何标准库头之外,import std;特别是如果一个项目依赖于 Boost 之类的东西,那么在 Boost 本身作为模块提供之前,这似乎不是一个现实的选择,对吗?

那么与此同时,我的说法对吗?import std; is basically only realistic for new or small projects where the standard library header dependencies (both direct and transitive) can be fully tracked and migrated at the same time? Or is there a way to somehow migrate a project to import std; even if some of its dependencies have not yet migrated?

如果我使用 Microsoft (R) C/C++ Optimizing Compiler Version 19.37.32824 for x64 编译以下代码,那么我会得到 C2572,这确实表明传递#includes cannot be mixed with import std;.

头文件.hpp

#include <iostream>
Run Code Online (Sandbox Code Playgroud)

主程序

#include "header.hpp"
import std;
int main() {
  std::cout << "Hello, world!\n";
}
Run Code Online (Sandbox Code Playgroud)
C:\Code\import-std-test>cl /std:c++latest /EHsc /nologo /W4 /MTd "%VCToolsInstallDir%\modules\std.ixx" main.cpp
std.ixx
main.cpp
C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.37.32822\include\xtr1common(42): error C2572: 'std::enable_if': redefinition of default argument: parameter 1
C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.37.32822\include\xtr1common(43): note: see declaration of 'std::enable_if'
main.cpp(5): fatal error C1117: unrecoverable error importing module 'std': symbol 'byte' has already been defined
Generating Code...
Run Code Online (Sandbox Code Playgroud)

swe*_*mer 3

感谢 @BoP 的评论,现在很清楚,混合import std;#include <header>应该可以工作,但只是尚未在 MSVC 中实现(不幸的是,教程中没有提到这一事实)。链接的谈话没有提到它何时可用,但听起来微软正在积极研究它。

因此,回答最初的问题:不,import std;对于大多数项目来说,目前这不是一个现实的目标,但是,是的,当 MSVC 完全实现该标准时,这将是一个现实的目标,它允许将两者混合。