Home  >  Article  >  Backend Development  >  How to Achieve Reflection-like Functionality in C Using std::map?

How to Achieve Reflection-like Functionality in C Using std::map?

DDD
DDDOriginal
2024-10-27 01:22:30895browse

How to Achieve Reflection-like Functionality in C   Using std::map?

How to Call a Function by Its Name (std::string) in C

In C , it's common to use conditional statements to call functions based on a given string. However, this approach can be verbose and inflexible.

Reflection in C

The ability to call a function by its name is known as reflection. Unfortunately, C doesn't natively support this feature.

Workaround Using std::map

One workaround is to create a std::map that associates function names (std::string) with function pointers. For functions with the same prototype, this technique simplifies the process:

<code class="cpp">#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() {
    // Initialize the map:
    std::map<std::string, FnPtr> myMap;
    myMap["add"] = add;
    myMap["sub"] = sub;

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

In this example, myMap[s](2, 3) retrieves the function pointer mapped to the string s and invokes the corresponding function with arguments 2 and 3. The output would be 5.

The above is the detailed content of How to Achieve Reflection-like Functionality in C Using std::map?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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