1

Say I have the following code:

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

}

Is it possible to do this in some way? If not could you recommend a method to accomplish the same thing?

2 Answers2

0

You could use (partial) template specialisation:

// 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());
    }
isedev
  • 18,848
  • 3
  • 60
  • 59
0

Here are 2 ways of doing it:

1) Template specialization (making a special case for a template argument (here: 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) Using typeid to compare the types

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;
}
Rakete1111
  • 47,013
  • 16
  • 123
  • 162
  • 1
    This is different from actual question, when hf is member of the class. There is also no guarantee that comparing `typeid()` of the same type will yield true. – SergeyA Mar 31 '16 at 13:06
  • Thanks! `hash_code()` is guaranteed to be the same for the same types. – Rakete1111 Mar 31 '16 at 16:34