簡體   English   中英

類模板和函子

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM