在C++中初始化模板时,将函数传递给模板对象
Passing function to template object when initializing template in C++
我正在尝试为哈希映射编写一个实现,除了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函数进行编码。
不知道我为什么要这样包,但它有效。在这里找到了它的细节
相关文章:
- 如何使用单独文件中的派生类访问友元函数对象
- 当使用透明的std函数对象时,我们还需要写空的尖括号吗
- 有没有办法将重载的类函数绑定到函数对象?
- 将指针传递到成员的指针,从模板参数包到函数对象
- 如何在类模板的成员函数中正确调用函数对象?正在生成 Visual Studio 编译器错误 C2440
- 隐式转换为比较函数对象(函子)用于 std::sort 而不是 std::map?
- C++使用函数对象的线程,如何调用多个析构函数而不是构造函数?
- 如何通过接口将函子分配给函数对象
- 对std::函数对象的调用不匹配,该对象是指向成员函数的指针
- 指向std::invoke中成员函数对象的指针
- 如何成功地将函数对象(或lambda)传递给trackbar回调的第二个参数(void*)
- "std::function"的简单版本:函数对象的生存期?
- C++ 将函数对象作为左值和/或右值传递
- SFINAE 用于具有默认参数的函数对象
- 构造函数对象赋值是否泄漏内存
- 如何发送通过绑定到函数/方法创建的函数对象?
- std::for_each 与函数对象
- 将函数对象传递给 std::function
- 访问执行策略for_each函数对象中的迭代器
- 通过C++函数对象类访问参数