'Conditionally import a module on C++20
Is there a way to conditionally import a module on C++20 without a preprocessor directive?
pseudo-code:
if WINDOWS:
import my_module;
else:
import other_module;
If there's no way, what would be the cleanest way of do it with the preprocessor?
Solution 1:[1]
If your goal is to have multiple implementations of the same functionality (for example, platform dependent) then cleaner way of doing this is to have multiple implementation units for the common module interface.
For example, we want to have "my_module" module that provides platform dependent functionality void show_notification(std::string).
We can have one common module interface file "my_module.ixx" that contains declarations:
// my_module.ixx
export module my_module;
import <string>;
export void show_notification(std::string text);
Then we can have multiple module implementation units, one for each of the platforms:
// my_module_windows.cpp
module;
// Windows specific includes
module my_module;
// Windows specific includes
void show_notification(std::string text) {
// Windows specific code ...
}
// my_module_linux.cpp
module;
// Linux specific includes
module my_module;
// Linux specific includes
void show_notification(std::string text) {
// Linux specific code ...
}
Both my_module_linux.cpp and my_module_windows.cpp provides implementation for my_module.
Then we can use build system to include suitable module implementation unit in our build depending on platform or other settings.
For example if we include my_module_windows.cpp in the set of translation units of our project we would have windows implementation.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Serikov |
