2013-11-09 51 views
0

我真的不知道該怎麼辦。我看到的每個答案都有我不明白的語法。錯誤C2064使用<functional>和<bind>

錯誤:

Error 1 error C2064: term does not evaluate to a function taking 1 arguments 

我使用哈希表的構造函數指針。有人建議我使用頭文件來解決我遇到的問題。它解決了錯誤,但我遇到了上述錯誤。

我的哈希表的聲明和構造函數如下:

#pragma once 
#include "SLList.h" 

template<typename Type> class HTable 
{ 
public: 
    HTable(unsigned int numOfBuckets, std::function<unsigned int(const Type&)>   hFunction); 
    ~HTable(); 
    HTable<Type>& operator=(const HTable<Type>& that); 
    HTable(const HTable<Type>& that); 
    void insert(const Type& v); 
    bool findAndRemove(const Type& v); 
    void clear(); 
    int find(const Type& v) const; 

private: 
    SLList<Type>* ht; 
    std::function<unsigned int(const Type&)> hFunct; 
    unsigned int numOfBuck; 
}; 

template<typename Type> 
HTable<Type>:: HTable(unsigned int numOfBuckets, std::function<unsigned int(const  Type&)> hFunction) 
{ 
    ht = new SLList<Type>[numOfBuckets]; 
    this->numOfBuck = numOfBuckets; 
    this->hFunct = hFunction; 
} 

Game.h(含表):

#pragma once 

#include "stdafx.h" 
#include "HTable.h" 
#include "BST.h" 
#include "DTSTimer.h" 

using namespace std; 

class Game 
{ 
public: 
    Game(void); 
    virtual ~Game(void); 
    void refresh(); 
    void input(); 
    unsigned int xorHash(const string &s); 

private: 
    string userInput; 
    DTSTimer timer; 
    BST<string> answers; 
    HTable<string> dictionary; 
}; 

Game.cpp(我試圖在xorHash函數傳遞)

#include "Game.h" 


Game::Game(void) : dictionary(2048, std::bind(&Game::xorHash, this)) 
{ 

} 


Game::~Game(void) 
{ 

} 

void Game::refresh() 
{ 

} 

void Game::input() 
{ 

} 

unsigned int Game::xorHash(const string &s) 
{ 
    return 0; 
} 

在此先感謝。

回答

0

您需要爲未綁定的函數參數的佔位符:

std::bind(&Game::xorHash, this, std::placeholders::_1) 

一個lambda可能更可讀,可根據口味:

[this](const std::string & s){return xorHash(s);} 

儘管這不是很清楚,我爲什麼xorHash需求是一個非靜態成員;當然,一個散列應該只取決於它的輸入?

0

xorHash是一種需要1個參數的方法。這意味着它也暗指需要一個this指針。

使之成爲static方法或class以外的自由函數。

+0

這很好,如果它不需要是一個非靜態成員。否則,你想在OP嘗試時使用'function'和'bind'。 –

0

您想要傳遞的散列函數對象仍然需要將散列值作爲參數。這是你要綁定類似

std::bind(&Game::xorHash, this, std::placeholders::_1) 

需要的_1位告訴std::bind()其中一個參數有去送有哪一個(哪一次不是在這一背景下,有趣會有隻有一個;如果你是綁定接收多個參數的函數,它會更有趣)。

請注意,它實際上不太可能要傳遞一個真實的成員函數:通常,計算的散列值並不取決於對象狀態,也就是說,您可能最好使用xorHash()static成員函數並通過這一個:這種方式你甚至不需要std::bind()任何參數。

+0

這解決了這個問題。不幸的是,我不能太在意發動機罩下面發生了什麼,因爲我必須在星期一得到這整件事情,而我的老師幾乎沒有給出任何方向。在編寫實際的xorHash函數時,有什麼特別的我需要知道嗎? – rearden