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.
The ability to call a function by its name is known as reflection. Unfortunately, C doesn't natively support this feature.
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!