Ale*_*ara 6 c++ c++20 c++-modules
有没有办法在没有预处理器指令的情况下有条件地导入模块C++20?
伪代码:
if WINDOWS:
import my_module;
else:
import other_module;
Run Code Online (Sandbox Code Playgroud)
如果没有办法,使用预处理器最干净的方法是什么?
如果您的目标是拥有相同功能的多个实现(例如,依赖于平台),那么更简洁的方法是为公共模块接口拥有多个实现单元。
例如,我们希望有一个提供平台相关功能的“my_module”模块void show_notification(std::string)。
我们可以拥有一个包含声明的通用模块接口文件“my_module.ixx”:
// my_module.ixx
export module my_module;
import <string>;
export void show_notification(std::string text);
Run Code Online (Sandbox Code Playgroud)
然后我们可以有多个模块实现单元,每个平台一个:
// my_module_windows.cpp
module;
// Windows specific includes
module my_module;
// Windows specific includes
void show_notification(std::string text) {
// Windows specific code ...
}
Run Code Online (Sandbox Code Playgroud)
// my_module_linux.cpp
module;
// Linux specific includes
module my_module;
// Linux specific includes
void show_notification(std::string text) {
// Linux specific code ...
}
Run Code Online (Sandbox Code Playgroud)
和my_module_linux.cpp都my_module_windows.cpp提供了my_module.
然后我们可以使用构建系统根据平台或其他设置在我们的构建中包含合适的模块实现单元。
例如,如果我们将my_module_windows.cpp项目的翻译单元包含在其中,我们将拥有 Windows 实现。