我目前正在使用 Visual Studio 2022 Update 17.1.6,我發現匯出型別別名很有趣。由于我不明白的原因,當我為某些資料型別(例如std::vector<std::string>在模塊介面檔案中)匯出型別別名時,我可以在匯入它的檔案中同時使用std::vector<>和std::string。例如:
modInterface.ixx
export module words;
import <iostream>
import <vector>;
import <string>;
...
export using Words = std::vector<std::string>;
...
在內部磁區中:
modInternalPartition.cpp
module words:wordsIP;
import words;
//This compiles as expected
Words wordStorage;
//Why does my compiler sees below as correct, and compiles it without error?
std::vector<int> numStorage = { 1, 2, 3, 4 };
//Why does my compiler also sees below as correct, and compiles it without error?
std::string text = "This dish is tasty";
//This would produce an error, which is expected since I did not export import <iostream> in modInterface.ixx
std::cout << text;
...
我的第一個想法是,因為Words是型別別名,所以匯出它就意味著匯出std::vector<>和std::string,但是既然std::vector<>是模板,為什么不是只std::vector<std::string>匯出它的實體化()?
uj5u.com熱心網友回復:
當一個模塊的一個部分匯入另一個時,所有不受內部鏈接影響的宣告都可以使用,就像它們被匯出一樣。這甚至適用于import宣告(以及通過其非磁區實作單元隱式匯入模塊),因此import <vector>; 等。words:wordsIP在磁區中可用。與export它完全無關。
uj5u.com熱心網友回復:
這是關于模塊的一個有趣的事情:export宣告只對模塊外部的代碼很重要。
如果您匯入與您自己屬于同一模塊的模塊單元,則您可以訪問該模塊單元中的所有宣告。這允許您擁有不匯出到模塊介面的“私有”宣告,但模塊中的其他代碼仍然可以訪問這些宣告。這包括模塊匯入:
此外,當某個模塊 M 的一個模塊單元中的模塊匯入宣告匯入 M 的另一個模塊單元 U 時,它還匯入了由 U 的模塊單元范圍內的非匯出模塊匯入宣告匯入的所有翻譯單元。
標題單元在這方面并不特殊。您匯入了這些標頭單元,因此它們由您的主模塊介面匯入。因此,匯入主模塊介面的該模塊的任何模塊實作都將看到它們。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/473700.html
上一篇:使用模板引數將函式分配給函式指標
