0

我正在尝试利用 C++ 的部分模板专业化功能。

// 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 {
    ...
}

我希望HashSet声明的第二个模板参数hashf将对应于 struct GlobalHash的第一个声明,即具有 2 个模板参数的声明。看起来,编译器不能这样做,告诉我类模板GlobalHash需要 2 个模板参数。

我怎样才能让它带 1 个参数的类模板?很多谢谢!

4

1 回答 1

3

如果你想让模板参数有一个默认值,你可以这样写:

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

现在GlobalHash<int>GlobalHash<int, char>.

于 2019-11-28T12:33:48.153 回答