C++模板专用化 - 将其他整数类型委托给uint64_t
C++ template specialization - delegating other integer types to uint64_t
>我正在尝试为整数类型实现自定义哈希函子以用于std::unordered_map
.我想通过为无符号 64 位整数提供一个实现并通过强制转换/加宽将所有其他实现委托给该实现来做到这一点。
我过去已经成功地做到了这一点,只需为我想要的每种附加类型定义专业化:
template <typename T> struct custom_hash { size_t operator()(const T&) const };
template <> struct custom_hash<uint64_t> { size_t operator()(uint64_t x) const { /* ... */ }};
template <> struct custom_hash<int> { custom_hash<uint64_t> h; size_t operator()(int x) const { return h(x); }};
/* ... */
但是我想知道如何做到这一点,而无需对每种其他类型进行专业化。
我尝试了使用std::enable_if
和std::is_integral
在 SO 上阅读的内容:
template <typename T> struct custom_hash { /* ... */ };
template <> struct custom_hash<uint64_t> { /* ... */ };
template <typename Int, typename = typename enable_if<is_integral<Int>::value, Int>::type>
struct custom_hash<Int> {
custom_hash<uint64_t> h;
size_t operator()(Int x) const {
return h(x);
}
};
但这没有用。叮当
抱怨错误:类模板部分中的默认模板参数 专业化
和
错误:模板重新声明中的模板参数过多
我认为发生这种情况是因为该声明与先前没有定义的声明发生冲突。我对模板的了解不足以解决这个问题。
问题是模板专用化的所有模板参数都必须从基本模板中推导,而不是彼此推导。
如果你可以在基本模板中添加一个虚拟参数,或者在你控制的基础中进行特化,那么你就是黄金:
template <typename T, class = void>
struct custom_hash;
template <>
struct custom_hash<uint64_t>
{ size_t operator()(uint64_t x) const { /* ... */ }};
template <class T>
struct custom_hash<T, std::enable_if_t<std::is_integral<T>() && sizeof(T) <= sizeof(uint64_t)>
{ size_t operator()(int x) const { custom_hash<uint64_t> h; return h(uint64_t(x)); }};
相关文章:
- ArduinoJson 6.15.2:JsonObject没有命名类型
- 防止主数据类型C++的隐式转换
- 大量序列中核苷酸类型的快速计数
- 如何从C++中的依赖类型中获得它所依赖的类型
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- 是否可以初始化不可复制类型的成员变量(或基类)
- 如何获取std::result_of函数的返回类型
- 从父命名空间重载类型
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- Openssl 1.1.1d无效使用不完整的类型"struct dsa_st"
- 访问者访问变体并返回不同类型时出错
- 在VS2010-VS2015下编译时,如何使用decltype作为较大类型表达式的LHS
- 处理小于cpu数据总线的数据类型.(c++转换为机器代码)
- C++ 雷神库 - 使用资源加载器类时出现问题(不命名类型)
- 模板元程序查找相似的连续类型名称
- 是否可以从int转换为enum类类型
- 将模板类型名称转换为 uint64
- 如果FF的参数为UINT64类型,则无法返回正确的结果
- 警告 639:二进制操作中类型 'uint64' 的强类型不匹配