gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:16:19 24 4
gpt4 key购买 nike

我正在尝试为 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com