如何通过名称调用函数。一种使用STL :: map和Class的方法 [英] How to call a function by its name. An approach using STL::map and Class

查看:267
本文介绍了如何通过名称调用函数。一种使用STL :: map和Class的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据帖子如何通过C ++中的名称(std :: string)调用函数?,尝试使用CLASS创建一个版本,但我的方法不工作。

Based on post How to call a function by its name (std::string) in C++?, tried to make a version using CLASS, but my approach does not work.

class A {
    public:
        int add(int i, int j) { return i+j; }
        int sub(int i, int j) { return i-j; }
};

typedef int (*FnPtr)(int, int);

int main(int argc, char* argv[]) {

// initialization:
std::map<std::string, FnPtr> myMap;
A a;
myMap["add"] = a.add;
myMap["sub"] = a.sub;

返回此错误:

main.cpp:31:22: error: cannot convert ‘A::add’ from type ‘int (A::)(int, int)’ to type ‘std::map<std::basic_string<char>, int (*)(int, int)>::mapped_type {aka int (*)(int, int)}’
main.cpp:32:22: error: cannot convert ‘A::sub’ from type ‘int (A::)(int, int)’ to type ‘std::map<std::basic_string<char>, int (*)(int, int)>::mapped_type {aka int (*)(int, int)}’

有谁知道错误是什么?

Does anyone know what is the error?

推荐答案

至少如你所示, A类只提供问题。如果你把它变成一个命名空间,事情会很容易。

At least as you've shown things, your class A provides nothing but problems. If you turn it into a namespace, things will be a lot easier.

namespace A {
    int add(int i, int j) { return i+j; }
    int sub(int i, int j) { return i-j; }
};

typedef int (*FnPtr)(int, int);

int main(int argc, char* argv[]) {
    std::map<std::string, FnPtr> myMap;
    myMap["add"] = A::add;
    myMap["sub"] = A::sub;
    // ...

这样, code>和 sub 不是成员函数,因此不会得到类型不匹配。至少如图所示, A 的实例除了调用 add sub ,所以命名空间完成同样多的好,同时消除了问题。

This way, add and sub aren't member functions, so you don't get the type mismatch. At least as shown, the instance of A provided no functionality beyond calling add and sub, so a namespace accomplishes just as much good while eliminating the problems.

这篇关于如何通过名称调用函数。一种使用STL :: map和Class的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆