這個問題在這里已經有了答案: std::enable_if 是如何作業的? (2 個回答) 10 天前關閉。
template<classT>
class MyClass {
using KeyType = int;
using MapType = std::map<KeyType, int64_t>;
MapType map_;
template <class T1 = T, class = std::enable_if_t<std::is_same<T1, int>{}>>
IndexValueType LowerBound(KeyType k) const {
auto it = map_.lower_bound(k);
if (it == map_.end()) {
return NOT_FOUND;
}
return it->second;
}
};
這兩個作業在這種情況下做了什么?
class T1 = Tclass = std::enable_if_t<std::is_same<T1, int>{}>
uj5u.com熱心網友回復:
LowerBound是在類模板中宣告的成員模板函式。它類似于函式模板,但它包含在一個類(模板)中。 MyClass
代碼可以簡化為
template <typename T>
class MyClass {
template <typename T1 = T, typename = std::enable_if_t<std::is_same<T1, int>{}>>
IndexValueType LowerBound(KeyType k) const {}
};
第一個賦值T1 = T意味著第一個模板形參的默認T實參與. 如果您沒有明確指定,T1將是T. 您當然可以明確指定其他型別。
這里的第二個任務是std::enable_if. 評論中還指出,這是應用SFINAE的一種簡單方法。在這里它將禁用(忽略)模板T1與int. 由于第二個引數只是對第一個引數的限制,在定義中沒有任何用途,所以忽略了它的名字。
MyClass<int> mc1; // T is int
mc1.LowerBound(...) // T1 is int, when not specified explicitly
mc1.LowerBound<std::int32_t>(...) // T1 is std::int32_t here
MyClass<double> mc2; // T is double
mc2.LowerBound<int>(...) // OK, T1 is int
mc2.LowerBound(...) // T1 is substitued with double here and will cause compile error since is not int
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/428013.html
