有没有一种方法可以检查模板的数据类型
Is there a way to check what datatype a template is?
假设我有以下代码:
template<typename K, typename V>
int Hash<K, V>::hf(const K& key)
{
if(K == typeid(string))
{
return MurmurHash2(key.c_str(), key.size());
}
else
{
return key*2654435761;
}
}
有可能以某种方式做到这一点吗?如果没有,你能推荐一种方法来完成同样的事情吗?
您可以使用(部分)模板专业化:
// general case
template <typename K, typename V>
int Hash<K, V>::hf(const K& key)
{
return key*2654435761;
}
// string case
template <typename V>
int Hash<std::string, V>::hf(const std::string& key)
{
return MurmurHash2(key.c_str(), key.size());
}
这里有两种方法:
1) 模板专门化(为模板参数(此处:std::string
)设置特殊情况)
template<typename K, typename V>
int Hash(const K& key)
{
return key * 2654435761;
}
template<typename V>
int Hash(const std::string& key)
{
return MurmurHash2(key.c_str(), key.size());
}
2) 使用typeid
比较类型
template<typename K, typename V>
int Hash(const K& key)
{
if (typeid(K).hash_code() == typeid(std::string).hash_code())
return MurmurHash2(key.c_str(), key.size());
return key * 2654435761;
}
相关文章:
- 如何在 CPP 中检查给定输入的数据类型?
- C++ - 检查结构数据类型中的单词是否为回文
- BoostSpirit.Qi-针对原始数据类型进行边界检查
- 输入数据类型检查循环未按预期工作 (C++)
- 在编译时检查特征类型保存的数据在内存中是否连续
- 如何检查程序是否超过数据类型存储
- 检查模板函数的数据类型
- 如何便携式检查SuSv3数据类型的极值
- c++检查xs:double数据类型
- 有没有一种方法可以检查模板的数据类型
- 如何在C++中检查数据类型
- 如何使用 cppunit 断言宏来检查返回数据类型的预处理器值
- 如何根据 2 个枚举值检查创建具有 2 个数据类型参数C++模板类
- 检查长类型数据是否在 int 范围内的便携式方法是什么?
- 对字符串和基本数据类型应用大于或小于检查
- 是否有一种仅使用基本概念检查输入数据类型的方法
- 如何检查字符串中值的数据类型
- 如何检查数据类型是否为数组?(c++)
- 如果我将数字存储为整数数据类型,如何检查另一个数字中是否存在一个数字
- 检查int数据类型的输入是否有效