2014-11-15 83 views

回答

3

這叫做反射。你使用的是C++ 11嗎?如果是這樣看着函數。一種做你想做的事的方法是製作一個函數指針的映射,其名稱是字符串鍵。

#include <iostream> 
#include <map> 

int Func1() {} 
int Func2() {} 

typedef void (*FunctionPtr)(void); 

int main() { 

    std::map<std::string, void (*FunctionPtr)(void)> map; 
    map["Func1"] = Func1; 
    map["Func2"] = Func2; 

    myMap["Func1"](); 
} 
6

您可以創建一個std::mapstd::functionC++11

std::map<std::string, std::function<void()> > call; 

    call["func1"] = func1 ; 
    call["func2"] = func2 ; 

然後,

call["func1"]() ; 
+0

'的std :: function'似乎矯枉過正這一個。爲什麼不是簡單的函數指針? – Quentin

+1

@Quentin恕我直言,它更乾淨,更簡單 – P0W

+0

我很想知道downvotes的原因 – P0W

相關問題