2012-04-24 2 views
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()()

를 사용하여 동일한을 달성 할 수있는 방법이있다 이 같은
+0

적절한 페이지를 사용하십시오 구두점! – Nawaz

+0

정확히 무엇을하고 싶습니까? 클래스에서'get_hash_value'를 호출 할 수 없습니까? – juanchopanza

+0

'get_hash_value()'는'this'에 의존하지 않으므로 정적이어야합니다. 그런 다음 일반 함수 포인터로 사용할 수 있습니다. – RedX

답변

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
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; 
    } 
};