有没有一种方法可以检查模板的数据类型

Is there a way to check what datatype a template is?

本文关键字:检查 数据类型 方法 一种 有没有      更新时间:2023-10-16

假设我有以下代码:

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;
}