C++ 通过C+中无序映射包装器中的构造函数调用std::hash()+;

C++ 通过C+中无序映射包装器中的构造函数调用std::hash()+;,c++,template-specialization,unordered-map,C++,Template Specialization,Unordered Map,我们试图通过operator()(本例中为字符串)的模板专门化,或通过用户提供的键(此处为inKey)的HashFunction())的命令来设置mHashCode #包括 #包括 使用名称空间std; 模板类哈希函数 { 公众: HashFunction(const-Key&k); 内联运算符unsigned()常量 { 返回mHashCode; } size_t运算符()(常数键和k)常数; 私人: 无符号mHashCode; }; 模板HashFunction::HashFunction(

我们试图通过
operator()
(本例中为字符串)的模板专门化,或通过用户提供的键(此处为
inKey
)的
HashFunction()
)的命令来设置
mHashCode

#包括
#包括
使用名称空间std;
模板<类键>类哈希函数
{
公众:
HashFunction(const-Key&k);
内联运算符unsigned()常量
{
返回mHashCode;
}
size_t运算符()(常数键和k)常数;
私人:
无符号mHashCode;
};
模板HashFunction::HashFunction(conststring&k)
{
mHashCode=std::hash{}(k);
}
模板大小\u t HashFunction::operator()(const string&k)const
{
返回mHashCode;
}
模板>
类无序映射包装器
{
公众:
无序映射包装器();
私人:
无序地图*可移植;
};
模板
无序映射包装::无序映射包装()
{
mTable=新的无序地图(5);
}
int main(){
无序映射;
返回0;
}
如果用户将哈希函数(与
string
unsigned
等不匹配)与
hash()
构造函数一起传递,则此
mHashCode
是通过点击
HashFunction()
的命令生成的。在这种情况下,将创建
HashFunction
类的对象。由于这个原因,
mHashCode
将生成
operator()
的默认模板专门化将获得控制并返回
mHashCode
。i、 它只返回用户的值

模板专门化使用
运算符unsigned()
(构造函数的专门化),创建一个对象并返回
mHashCode

如果我们在模板参数的帮助下传递hash函数,并且默认情况下,它使用的是操作符(),而不是
HashFunction()
的命令,那么它就可以正常工作。如果像上面的代码片段那样使用c'tor,则会出现编译时错误

我们如何通过这个命令设置
mHashCode
,以便用户可以使用
std::Hash()
?我们的硬要求是需要通过c'tor调用
std::hash()
,而不是通过操作符


提前谢谢

。。。这里的目标是什么?您将遇到的一个问题是,
HashFunction
不是默认可构造的,这是它作为
std::hash
的替代品所必需的。需要有一个
HashFunction()
构造函数才能以这种方式使用此类型。哈希函数需要能够哈希多个字符串。如果您在构建时修复了哈希代码,它就无法修复。我们可以使用:
unordered_-map=unordered_-map(1,*(new pairHash())1表示
大小\类型\总线
#include <iostream>
#include <unordered_map>
using namespace std;

template< class Key > class HashFunction
{
  public:
    HashFunction( const Key & k );

    inline operator unsigned() const
    {
      return mHashCode;
    }
    size_t operator()(const Key &k) const;

  private:
    unsigned mHashCode;
};

template<> HashFunction< string >::HashFunction( const string & k )
{
  mHashCode=std::hash<string>{}(k);
}

template <> size_t HashFunction< string >::operator()(const string &k) const 
{
  return mHashCode;
}

template< class Key, class Val, class Hash = HashFunction< Key > >
class unordered_map_wrapper
{
  public:
   unordered_map_wrapper();
  private:
    unordered_map<Key, Val, Hash> * mTable;
};

template< class Key, class Val, class Hash >
unordered_map_wrapper< Key, Val, Hash >::unordered_map_wrapper()
{
    mTable=new unordered_map<Key, Val, Hash>(5);
}

int main() {
    unordered_map_wrapper<string, unsigned> h;
    return 0;
}