c++ - 调用函数的动态函数

标签 c++ c

假设有人按照以下方式分别为每个人做了单独的功能:

void John_age(void);
void Tom_age(void);
void Kate_age(void);
void Cathy_age(void);

......................

确定他们的年龄。

现在我想创建这样一个函数来仅使用人名来调用这些函数,例如:

void age(char* NAME){...}

为那个人“名字”调用特定函数。

void NAME_age(void);

在 C++ 或 C 中有什么简单的方法可以做到这一点吗?我将衷心感谢您的帮助。谢谢。

我用于微 Controller 的 IDE 为每个单独的引脚 X 生成格式为 void X_functionName(void); 的可执行函数。所以我一直在寻找一种更通用的方法来使用 void customName(const char* X) 等函数轻松调用它们。

最佳答案

这很容易。制作姓名与年龄功能的映射。
typedef 使函数指针更容易,而静态局部映射使其只被初始化一次,然后“缓存”结果。无序映射非常适合这类事情。

C++11:

void age(const std::string& NAME){
    static const std::unordered_map<std::string, void(*)()> age_lut = {
            {"John",John_age},
            {"Tom",Tom_age},
            {"Kate",Kate_age},
            {"Cathy",Cathy_age},
        };
    return age_lut.at(Name); //throws std::out_of_range if it doesn't exist
}

C:(这里我用的是线性映射而不是像C++那样的散列,因为我懒)

typedef void(*)() get_age_func_type; 
typedef struct {
    const char* name;
    get_age_func_type func;
} age_lut_type;

age_lut_type age_lookup_table[] = {
            {"John",John_age},
            {"Tom",Tom_age},
            {"Kate",Kate_age},
            {"Cathy",Cathy_age},
        };
const unsigned age_lookup_table_size = 
        sizeof(age_lookup_table)/sizeof(age_lut_type);

bool age(char* NAME){
    bool found = false;
    //if you have a large number of functions, 
    //sort them in the initialization function, and 
    //use a binary search here instead of linear.
    for(int i=0; i<age_lookup_table_size ; ++i) {
        if (stricmp(age_lookup_table[i], NAME)==0) {
            age_lookup_table[i].func();
            found = true;
            break;
        }
    }
    return found;
}

所有这些代码都不在我的脑海中,可能无法按原样编译。

实际上,我强烈建议不要为每个人设置函数,而是使用数据。如果绝对需要,请使用枚举而不是字符串来标识它们。

关于c++ - 调用函数的动态函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17532293/

相关文章:

c++ - 使用 VS2012 编译 libffi 失败并出现 fatal error LNK1281 : Unable to generate SAFESEH image

C++ Boost::asio与Arduino的串行通信无法写入

c++ - 如何在子类和父类的 header 中指定构造函数

c - 动态矩阵分配 - 使用 malloc 分配连续的整数 block 不起作用

c - 随 secret 码生成器相同的字符串

c++ - 如何使用 initializer_list 列表来初始化具有自定义类的 map

c++ - 为什么派生类指针在没有强制转换的情况下不能指向基类对象?

C编程错误: [undefined reference to: 'show_record' ]

c++ - 数组如何在 C/C++ 中内部工作

c - 在 C 中读取大缓冲区 - 高效技术