加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 07:14:27 所属栏目:百科 来源:网络整理
导读:我正在尝试为哈希映射编写一个实现,除了iostream,string和cassert之外,我不允许使用stdlib中的任何内容. 它必须是通用的,因此填充桶的值可以是任何类型.我需要模板,但无法以任何方式设置传递哈希函数.这将是头文件: templatetypename Value,typename hashFu
我正在尝试为哈希映射编写一个实现,除了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”.我想我可以传递指向函数的指针,但这似乎是一个黑客而不是一个真正的解决方案.有没有更好的办法?

解决方法

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读