类模板和仿函数

时间:2012-04-24 09:53:30

标签: c++ templates

我有以下课程

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

来实现同样的目标

2 个答案:

答案 0 :(得分: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();

答案 1 :(得分: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;
    }
};