2013-05-15 39 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); 

希望这会有所帮助。

相关问题