c++ - 在 C++ 中初始化模板时将函数传递给模板对象

标签 c++ templates hashmap parameter-passing hashtable

我正在尝试为 HashMap 编写一个实现,除了 iostream、string 和 cassert 之外,我不允许使用 stdlib 中的任何内容。

它需要是通用的,因此填充桶的值可以是任何类型。我为此需要模板,但无法设法以任何方式传递哈希函数。这将是头文件:

template<typename Value, typename hashFunction>
class hashTable{
    public:
      hashTable(int size){
        //Creates an empty vector of size on the table
      }
      define(Value v){
        loads value in Vector[hashFunction(v)];
      }
      ...
    private:
      Vector with all the elements
}

注意:我想我不需要 key 模板,对吧?

我无法在我的类中定义散列函数,因为我必须创建一个适用于所有类型(字符串到 int、int 到 int、double 到 int 等)的函数。所以我想唯一的解决办法是将函数作为参数传递到我的 main.这将是主要的。

int hashF(int v){return v}
int main(){
  hashTable<int,int,hashF> table(5);
}

但这行不通,g++ 告诉我“预期的类型但得到了 hashF”。我想我可以传递一个指向函数的指针,但这似乎是一种 hack 而不是真正的解决方案。有没有更好的办法?

最佳答案

template<typename Value, int(*fun)(Value)>
class hashTable {
  std::vector<Value> v;
public:
  hashTable(std::size_t size) : v(size) { }
  void define(Value &&val) { v[fun(val)]  = val; }
};

Live Demo

非函数指针方式:

template<typename Value, typename F>
class hashTable {
  std::vector<Value> v;
  F fun;
public:
  hashTable(std::size_t size, F fun_) : v(size), fun(fun_) { }
  void define(Value &&val) { v[fun(val)]  = val; }
};

Live Demo

关于c++ - 在 C++ 中初始化模板时将函数传递给模板对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33861811/

相关文章:

c++ - AVL 树和双向链表

c++ - 从类型包中解压缩模板-模板参数

c++ - 尝试定义一个接受模板参数的模板函数

c++ - C++ 中的通用访问者基类模板 - 重载问题

c++ - 在 C++ 中为 map 自动生成键

java - hashmap如何处理负hashcode?

java - 如何使用 Apache axis 在 Web 服务中使用 HashMap?

c++ - 多项式类

c++ - 对数字数组进行子采样

c++ - 模板类的重载赋值运算符