【问题标题】:Passing function to template object when initializing template in C++在 C++ 中初始化模板时将函数传递给模板对象
【发布时间】:2016-02-25 00:20:44
【问题描述】:

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

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

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

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

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

【问题讨论】:

  • 我从来没有弄清楚为什么你不能将一个简单的函数作为常规模板参数传递。如果你将它包装在一个结构中为operator() 你的代码仍然可以工作。
  • 我试试,谢谢!

标签: c++ templates hashmap parameter-passing hashtable


【解决方案1】:
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

【讨论】:

  • 谢谢!使用这样的函数指针是不是“危险”或不是最佳实践?
  • @DamianPereira 没有风险就没有乐趣。
  • 再次感谢,我会尝试两个,但我想我更喜欢无聊的版本,指针错误是地狱。
【解决方案2】:

在 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-25
    • 1970-01-01
    • 2011-11-15
    • 2016-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多