[英]Using class member variables that hold functions in definition of inner structures that will be used as template arguments of an unordered_map object
我正在實現一個使用unordered_map
的對象。 對象是通用的,因此模板無處不在。 特別是, operator==
和operator()
被包裝到unordered_map
使用的結構中,以分別檢查鍵是否相等並生成鍵的哈希值。 我希望用戶編寫自己的函數來實現上述兩個運算符,並將這些方法作為輸入傳遞給類對象。 然后,這些結構將使用這些對象。 我在使用示波器時遇到了麻煩,似乎無法弄清楚該怎么做。 這是我的代碼:
#include <unordered_map>
#include <iostream>
#include <string>
#include <functional>
template <typename O>
class aClass
{
public:
aClass( bool (usrIsEq)(O, O) ,
std::size_t (usrHashFtn)(O) )
{
this->usrIsEq = usrIsEq;
this->usrHashFtn = usrHashFtn;
}
void add(O k, std::string v)
{
iTable[ {k} ] = v;
}
std::string get(O k)
{
return iTable[ {k} ];
}
private:
bool (*usrIsEq)(O, O);
std::size_t (*usrHashFtn)(O);
struct Key
{
O obj;
bool operator==(const Key &other) const
{
std::cout << "obj " << obj << std::endl;
return usrIsEq(obj, other.obj);
}
};
struct KeyHasher
{
std::size_t operator()(const Key &k) const
{
return usrHashFtn(k);
}
};
std::unordered_map<Key, std::string, KeyHasher> iTable;
};
bool isEqInts(int a, int b)
{
return a == b;
}
std::size_t intHashFtn(int x)
{
std::hash<int> hf;
return hf(x);
}
int main()
{
aClass<int> x(isEqInts, intHashFtn);
x.add( 1, std::string("hello") );
}
我不完全確定如何實現struct
的Key
和KeyHasher
以便它們使用類中包含的功能。 我真正關心的唯一事情是,這些函數是作為類構造函數的輸入提供的。 其他一切都可以報廢。
使您usrIsEq
的主要問題是Key
不了解usrIsEq
而KeyHasher
不了解usrHashFtn
。 您需要將指向aClass
對象的指針或引用aClass
給這些類。
這是一個建議:
struct Key
{
O obj;
aClass* ac;
bool operator==(const Key &other) const
{
std::cout << "obj " << obj << std::endl;
return ac->usrIsEq(obj, other.obj);
}
};
struct KeyHasher
{
std::size_t operator()(const Key &k) const
{
return k.ac->usrHashFtn(k.obj);
}
};
並更新您使用Key
訪問表的位置:
void add(O k, std::string v)
{
iTable[{k, this}] = v;
}
std::string get(O k)
{
return iTable[{k, this}];
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.