2016-10-17 26 views
2
std::unordered_map<std::string, std::string> mimeMap = { 
    #define STR_PAIR(K,V) std::pair<std::string, std::string>(K,V) 
    #include "MimeTypes.inc" 
}; 

文件MimeTypes.inc unordered_map初始化是這樣的:用#include

STR_PAIR("3dm", "x-world/x-3dmf"), 
STR_PAIR("3dmf", "x-world/x-3dmf"), 
STR_PAIR("a", "application/octet-stream"), 
STR_PAIR("aab", "application/x-authorware-bin"), 
STR_PAIR("aam", "application/x-authorware-map"), 
STR_PAIR("aas", "application/x-authorware-seg"), 
STR_PAIR("abc", "text/vnd.abc"), 
STR_PAIR("acgi", "text/html"), 
STR_PAIR("afl", "video/animaflex"), 
STR_PAIR("ai", "application/postscript"), 
STR_PAIR("aif", "audio/aiff"), 

我很迷茫。這段代碼如何初始化一個unordered_map

回答

8

#include沒有文字複製粘貼。這幾乎就像你寫的直接執行以下操作:

std::unordered_map<std::string, std::string> mimeMap = { 
    #define STR_PAIR(K,V) std::pair<std::string, std::string>(K,V) 
    STR_PAIR("3dm", "x-world/x-3dmf"), 
    // ... 
    STR_PAIR("aif", "audio/aiff"), 
}; 

現在,STR_PAIR是預處理宏與std::pair<std::string, std::string>(K,V)KV是宏的參數代替它的參數。例如,上面的代碼是沒有什麼不同:

std::unordered_map<std::string, std::string> mimeMap = { 
    std::pair<std::string, std::string>("3dm", "x-world/x-3dmf"), 
    // ... 
    std::pair<std::string, std::string>("aif", "audio/aiff"), 
}; 

如果你正在使用gcc或鏗鏘,您可以使用-E命令行選項來獲得預處理輸出,看看自己。請注意,它會很大,但。

最後,這樣的pair用於複製初始化mimeMap的元素。

此代碼也馬車,因爲mapvalue_typepair<const Key, Value>,所以STR_PAIR實際上應該創建std::pair<std::string const, std::string>

+0

很好的提及_buggy aspect_。 +1 –

+0

實際上越野車是否保證了轉換? (我同意不應該這樣寫) –

+0

據我所知,它是「定義明確的」,並且確實(主要)是程序員的意圖,但是同時配對'和''是不同的類型。 – krzaq

1

reference documentation你必須使用一個std::initializer_list構造(5)的選項:

map(std::initializer_list<value_type> init, 
    const Compare& comp = Compare(), 
    const Allocator& alloc = Allocator()); 

宏從std::pair s和#include d構建一個irective取代{}括號內的文字。最後,評估結果如下:

std::unordered_map<std::string, std::string> mimeMap = { 
    #define STR_PAIR(K,V) std::pair<std::string, std::string>(K,V) 
    std::pair<std::string, std::string>("3dm", "x-world/x-3dmf"), 
    std::pair<std::string, std::string>("3dmf", "x-world/x-3dmf"), 
    std::pair<std::string, std::string>("a", "application/octet-stream"), 
    std::pair<std::string, std::string>("aab", "application/x-authorware-bin"), 
    std::pair<std::string, std::string>("aam", "application/x-authorware-map"), 
    std::pair<std::string, std::string>("aas", "a"); 
    std::pair<std::string, std::string>(pplication/x-authorware-seg"), 
    std::pair<std::string, std::string>("abc", "text/vnd.abc"), 
    std::pair<std::string, std::string>("acgi", "text/html"), 
    std::pair<std::string, std::string>("afl", "video/animaflex"), 
    std::pair<std::string, std::string>("ai", "application/postscript"), 
    std::pair<std::string, std::string>("aif", "audio/aiff"),  
};