Home > Backend Development > C++ > How Can I Call Functions by Name (Stored in a std::string) in C ?

How Can I Call Functions by Name (Stored in a std::string) in C ?

Patricia Arquette
Release: 2024-10-26 07:04:31
Original
1035 people have browsed it

How Can I Call Functions by Name (Stored in a std::string) in C  ?

Calling Functions by Name (std::string) in C

In C , one cannot directly call a function by name stored in a string. However, workarounds exist to achieve this functionality.

Basic Approach

The basic approach involves using a series of "if-else" statements or a "switch-case" construct, explicitly checking for the function name stored in the string and calling the corresponding function. As demonstrated in the provided code snippet, this method requires manually maintaining a list of functions and their names.

Reflection

The approach suggested in the question is referred to as reflection, which involves dynamically accessing and manipulating program elements at runtime. While reflection is not natively supported in C , some libraries provide limited reflection capabilities.

Workaround Using std::map

One workaround involves creating a std::map that associates function names (std::string keys) with function pointers (int (*FnPtr)(int, int) values). This allows for efficient retrieval and invocation of functions based on their names.

The provided code snippet illustrates this approach:

<code class="c++">#include <iostream>
#include <map>

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() {
    std::map<std::string, FnPtr> myMap;
    myMap["add"] = add;
    myMap["sub"] = sub;

    std::string s("add");
    int res = myMap[s](2, 3);
    std::cout << res;
}</code>
Copy after login

In this example, the myMap[s](2, 3) expression retrieves the function pointer associated with the string "add" and invokes it with arguments 2 and 3, resulting in an output of 5.

The above is the detailed content of How Can I Call Functions by Name (Stored in a std::string) in C ?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template