[英]class template and functor
我有以下课程
class hash_key {
public:
int get_hash_value(std::string &inStr, int inSize) const {
int hash = 0;
for(int i = 0; i < (int)inStr.size(); i++) {
int val = (int)inStr[i];
hash = (hash * 256 + val) % inSize;
}
return hash;
}
};
我想将其传递给我的另一个模板类,以便我可以调用get_hash_value
如何做到这一点,有什么方法可以使用operator()()
像这样:
class hash_key {
public:
hash_key(std::string& inStr, int inSize) : size(inSize), str(inStr) {}
int operator()() const
{
int hash = 0;
for(int i = 0; i < (int)str.size(); i++) {
int val = (int)str[i];
hash = (hash * 256 + val) % size;
}
return hash;
}
private:
std::string str;
int size;
};
Now you can do:
std::string str = "test";
hash_key key(str, str.size());
//pass below to template, calls `operator()()`
key();
struct hash_key {
public:
int operator()(std::string &inStr, int inSize) const {
int hash = 0;
for(int i = 0; i < (int)inStr.size(); i++) {
int val = (int)inStr[i];
hash = (hash * 256 + val) % inSize;
}
return hash;
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.