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

Passing function to template object when initializing template in C++

我正在尝试为散列映射编写一个实现,除了 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
}

注意:我想我不需要密钥模板,是吗?

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

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

但这行不通,g++ 告诉我 "expected type but got 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

根据 Neil 的建议设法让它工作。我的 hash.h:

template<typename C, typename D, typename H>
class Tabla {
public:
Tabla(int s){
    cout << hashF(3) << endl;
    size=s;
}
private:
    H hashF;
    int size;
};

我的hash.cpp

struct KeyHash {
unsigned long operator()(const int& k) const
{
    return k % 10;
}
};
int main(){
    Tabla<int,int,KeyHash> tab(3);
    return 0;
}

这个例子只是为了展示我能够使用模板中的函数,然后我必须编写使用该 KeyHash 的定义和删除函数的代码。

不知道为什么我必须这样包装它,但它确实有效。找到它的细节 here