module
、
import
和
export
宣告可在 C++20 中使用,而且需要編譯器開關
/std:c++20
或更新版本。 如需詳細資訊,請參閱
C++ 中的模組概觀
。
module
將
module
宣告放在模組實作檔案的開頭,以指定檔案內容屬於具名模組。
module ModuleA;
export
針對模組的主要介面檔案使用 export module
宣告,其擴展名預設為 .ixx
。 如果您想要使用不同的擴充功能,請使用 /interface 參數將其編譯為模組介面。
export module ModuleA;
在介面檔案中,對於預期要成為公用介面一部分的名稱,請使用export
修飾詞。
// ModuleA.ixx
export module ModuleA;
namespace ModuleA_NS
export int f();
export double d();
double internal_f(); // not exported
模組匯入後,程式碼無法看到未匯出的名稱:
import ModuleA;
int main() {
ModuleA_NS::f(); // OK
ModuleA_NS::d(); // OK
ModuleA_NS::internal_f(); // Ill-formed: error C2065: 'internal_f': undeclared identifier
關鍵詞 export
可能不會出現在模組實作檔案中。 當套用至命名空間名稱時 export
,會導出命名空間中的所有名稱。
import
import
使用宣告,讓模組的名稱在您的程序中可見。 宣告import
必須出現在module
聲明和任何#include
指示詞之後,但在檔案中的任何其他聲明之前。
module ModuleA;
#include "custom-lib.h"
import std;
import myModule;
// begin declarations here:
template <class T>
class Baz
{...};
只有在邏輯行的開頭出現時,import
和module
才會被視為關鍵詞。
// OK:
module ;
module module-name
import :
import <
import "
import module-name
export module ;
export module module-name
export import :
export import <
export import "
export import module-name
// Error:
int i; module ;
Microsoft 特定
在 Microsoft C++ 中,令牌 import
和 module
一律是識別符號,且在作為巨集的參數時,絕不是關鍵字。
#define foo(...) __VA_ARGS__
import // Always an identifier, never a keyword
結束Microsoft專屬內容
C++ 中的模組概觀
使用模組匯入C++標準連結庫