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;
}
};
这 2 个作业在这种情况下有什么作用?
-
class T1 = T
-
class = std::enable_if_t<std::is_same<T1, int>{}>
LowerBound
是一个 member template在 class template 中声明的函数我的类
。它类似于函数模板,但它包含在一个类(模板)中。
代码可以简化为
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