0

我有以下课程

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()()

4

2 回答 2

2

像这样的东西:

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();
于 2012-04-24T09:57:44.713 回答
1
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;
    }
};
于 2012-04-24T09:56:09.987 回答