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

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

本文关键字:函数 对象 C++ 初始化      更新时间:2023-10-16

我正在尝试为哈希映射编写一个实现,除了iostream、string和casert之外,我不允许使用stdlib中的任何东西。

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

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
}

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

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

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

但这不起作用,g++告诉我"预期类型但得到了hashF"。我想我可以把一个指针传给一个函数,但这似乎是一个破解,而不是一个真正的解决方案。有更好的方法吗?

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; }
};

实时演示

非功能指针方式:

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; }
};

实时演示

设法在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的define和delete函数进行编码。

不知道我为什么要这样包,但它有效。在这里找到了它的细节