我目前正在實作一個三向映射類,這意味著每個“索引”都有三個鍵,一個可以檢索每個鍵。函式get定義為:
template<typename returnType, typename getType>
returnType get(getType getVal) {
if (typeid(returnType) == typeid(getType)) {
return getVal;
}
// Here the appropriate value is gotten. Not important for this.
// This is returned just in-case nothing is found.
return *new returnType;
}
這不會編譯,因為 getType 并不總是等于 returnType,這是由我的檢查保證的。有沒有辦法進行編譯,因為獲取程序非常昂貴。我試著做return returnType(getVal);,只有當returnType有一個建構式時才有效getType。
我可以想象但沒有設法解決的解決方案:
- 模板專業化
- 禁用型別檢查(類似于 rust 的
unsafe)
PS:我知道這個優化沒有多大意義,仍然想知道是否可以編譯。
uj5u.com熱心網友回復:
typeid不打算在編譯時以這種方式使用。如果要在編譯時對型別進行操作,請使用#include<type_traits>. typeid如果您需要在運行時對型別進行操作(例如在容器中存盤型別的 id 或獲取型別的可列印名稱),或者您需要在運行時確定多型指標/左值的實際型別,則需要使用它。
要在編譯時比較型別,請使用std::is_same_v<returnType, getType>. 由于 C 17 還可以有條件地編譯if模板中的分支,使用if constexpr代替if:
template<typename returnType, typename getType>
returnType get(getType getVal) {
if constexpr (std::is_same_v<returnType, getType>) {
return getVal;
} else {
// Here the appropriate value is gotten. Not important for this.
// This is returned just in-case nothing is found.
return /*some returnType*/;
}
}
另請注意,應用于*運算式new實際上總是錯誤的。您將*new returnType立即按值回傳。這是有保證的立即記憶體泄漏。new回傳一個指向新分配記憶體的指標,其中包含給定型別的新物件。按值回傳取消參考的指標意味著這個新物件再次被復制到回傳值中,同時指向第一個新創建物件的左值/指標在復制/移動建構式中丟失。
要創建要直接回傳的物件,請不要使用new. 只需使用功能顯式轉換表示法回傳一個臨時物件:
return returnType{};
甚至更短,因為returnType在函式回傳型別中已經提到:
return {};
new在 C 中很少需要直接使用。如果上面的變數或臨時變數也有效,則不要使用new,如果這不起作用,請重新考慮是否不應該使用std::unique_ptr/ std::shared_ptr/ std::vector/ std::string/etc。而不是new.
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/508189.html
