2013-05-15 48 views
2

這是我的代碼。調用映射鍵調用需要參數的函數 - 如何獲得工作

#include <map> 
#include <string> 
#include <algorithm> 

class maptest { 
public: 
    int doubler(int val) { return val * 2; } 
    int halver(int val) { return val/2; } 
    int negativer(int val) { return val > 0 ? -val : val; } 
}; 


int main() { 

    const char* const ID[] = {"doubler", "halver", "negativer" }; 
    int ID_SIZE = sizeof(ID)/sizeof(*ID); 

    //signature of maths functions 
    typedef int (maptest::*mathfunc)(int); 


    mathfunc mfuncs[] = { &maptest::doubler, &maptest::halver, &maptest::negativer}; 

    std::map<std::string, mathfunc> mathmap; 

    for(int i = 0; i < ID_SIZE; ++i) { 
     mathmap.insert(std::make_pair(ID[i], mfuncs[i])); 
    } 

    //C2064: term does not evaluate to a function taking 1 argument 
    int result = *mathmap["doubler"](3); 

    return 0; 
} 

我認爲這將工作,如果沒有參數傳遞給函數。但是,如何以這種方式傳遞參數?

回答

3

mathfunc s爲成員函數,所以你需要一個對象上調用它們:

maptest mt; 
int result = (mt.*(mathmap["doubler"]))(3); 

或者,你可以讓你的成員函數靜:

class maptest { 
public: 
    static int doubler(int val) { return val * 2; } 
    static int halver(int val) { return val/2; } 
    static int negativer(int val) { return val > 0 ? -val : val; } 
}; 

,然後定義mathfunc相應地:

typedef int (*mathfunc)(int); 

而這個w烏爾德允許你調用它們在你原來的職位要調用它們的方式:

typedef int (*mathfunc)(int); 

通知書的,一種方法,使這種設計更加靈活的方式是利用std::function,這將讓你pass any type of callable object。例如:

typedef std::function<int(int)> mathfunc; 

mathfunc mfuncs[] = { 
    &maptest::doubler, 
    &maptest::halver, 
    &maptest::negativer, 
    [] (int i) { return i * 2; } // <== A LAMBDA... 
    }; 
+0

(mt。*(mathmap [「doubler」]))的包圍很混亂。爲什麼你需要外部包圍,即這裏的括號:(mt。*(mathmap [「doubler」]))? –

+0

@ user619818:這不是必需的,我只是認爲它使事情更清晰。也許我錯了;) –

+0

在我的VS2008編譯器上它是需要的。不管。 –

1

您正在調用非靜態成員函數。

執行以下操作。

maptest t; 

int (maptest::*tptr) (int) = mathmap["doubler"]; 

int result = (t.*tptr)(2); 

希望這會有所幫助。

相關問題