Yv Zuo
Yv Zuo

Reputation: 391

Partial Template Specialization Failed

I am trying to take advantage of the C++'s Partial Template Specialization feature.

// for HashMap
template <typename Key, typename Val>
struct GlobalHash : public unary_functor<HashCode, const MapPair<Key, Val>&> {
    HashCode operator()(const MapPair<Key, Val> &obj) override {
        return HashFuncs::global_hashf(reinterpret_cast<const char *>(&obj.key), sizeof(obj.key));
    }
};

template <typename T>
struct GlobalHash<T, char> : public unary_functor<HashCode, const T&> {
    HashCode operator()(const T &obj) override {
        return HashFuncs::global_hashf(reinterpret_cast<const char *>(&obj), sizeof(T));
    }
};
// real Hash Set
template <class Obj, class hashf = GlobalHash<Obj>>
class HashSet {
    ...
}

I was hoping the 2nd template argument of the declaration of HashSet, hashf, would correspond to the first declaration of struct GlobalHash, the one with 2 template arguments. As it seems, the compiler cannot do so, telling me that the class template GlobalHash would require 2 template arguments.

How can I let it take the class template with 1 arguments? Many thx!!!

Upvotes: 0

Views: 54

Answers (1)

If you want a template argument to have a default value, you can write it like this:

template <typename Key, typename Val = char>
struct GlobalHash : public ....... {
    .........
};

Now GlobalHash<int> is short for GlobalHash<int, char>.

Upvotes: 3

Related Questions