【问题标题】:Is there a way to check what datatype a template is?有没有办法检查模板是什么数据类型?
【发布时间】:2016-03-30 21:25:18
【问题描述】:

假设我有以下代码:

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

}

有可能以某种方式做到这一点吗?如果没有,您能推荐一种方法来完成同样的事情吗?

【问题讨论】:

  • 模板专业化?
  • @isedev,我更喜欢重载。
  • @isedev 你能举一个我以前从未使用过的模板专业化的例子吗?
  • @SergeyA:当K 不是string(内联和优化分开)时,重载不会引入不必要的代码吗?
  • @Iriketurtles 这可能有助于解释isedev 所写的内容:en.cppreference.com/w/cpp/language/template_specialization

标签: c++ template-classes


【解决方案1】:

您可以使用(部分)模板专业化:

// 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());
    }

【讨论】:

  • 我收到一些错误,提示无法将函数定义与现有减速匹配
【解决方案2】:

这里有两种方法:

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

【讨论】:

  • 当 hf 是班级成员时,这与实际问题不同。也不能保证比较相同类型的 typeid() 会得到 true。
  • 谢谢! hash_code() 保证对于相同的类型是相同的。
猜你喜欢
  • 2011-08-02
  • 2020-10-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-10
  • 1970-01-01
相关资源
最近更新 更多