0
考慮以下幾點:爲什麼無效的C++映射聲明在編譯時不會失敗?
#include <map>
#include <string>
struct Key {};
int main(int argc, const char** argv) {
std::map<Key, std::string> key_map;
key_map.insert(std::make_pair(Key(), "hello"));
return 0;
}
顯然,這將無法編譯,因爲Key
不提供比運營商少。但是,如果我註釋掉第二行main()
(僅留下map
聲明),它會進行編譯。
問題:這是爲什麼?模板std::map<K, V>
是否強制執行K
在聲明時提供小於運算符的約束?
換句話說,聲明映射並不會嘗試實例化相應的insert()方法。沒有理由實例化未使用的方法。類和它的默認構造函數實例化得很好,但是'insert()'不。 – cdhowie
沒錯,@cdhowie –