【发布时间】:2016-04-06 10:30:35
【问题描述】:
我正在练习使用template 构建一个可以接受不同类型的哈希表。
如何在编译时不知道类型的情况下实现hashFunction?
template<class K, class V>
class HashTable {
public:
vector<vector<Bucket<K, V> > > table;
...
size_t hashFunction(const K &k) {
//can't implement without knowing the runtime types
}
}
我猜我应该做类似的事情:
return hash<K>(k) % table.size();
更新:
感谢 R Sahu 的回答,现在我知道这是我不清楚的模板部分专业化部分。请参阅this 问题和this link 以供参考。
【问题讨论】:
-
我认为您(或至少是编译器)确实知道 compile 时的类型。除非您有办法在运行时根据其
typeid查看类型的大小,否则您无能为力。请注意,对于HashTable的每个实例化,编译器确切地知道K的类型。