I have a set of functions with the same number of arguments, but different names (suppose each implement different method). I have the name of the requested method in a string. Is it possible to call the corresponding function using the method name. to make it clear, suppose that I have the following function (I just mentioned their name and argument):
search_esa(int a, int b);
search_tss(int a, int b);
search_fss(int a, int b);
search_ds(int a, int b);
now lets assume I have the name of the requested method, lets assume esa, in a string:
string methodName = "esa"
is it possible to call the corresponding function by using macros? I tested
#define CALL_SEARCH_MV(method) search_##method
and then try to call it by:
CALL_SEARCH_MV(methodName.c_str())
but it calls search_methodName function, which does not exist. Any other suggestions would be greatly appreciated (except suggesting switch case method or if).
You can use a combination of Macros, function pointers and clever hacking to achieve the desired result with ease.
In your main.cpp (or where the search functionality lives):
#include <map>
#include <string>
#include <iostream>
typedef int(*search)(int a, int b);
#define SEARCH(x) int search_##x(int a, int b);
#include "search_func.incl"
#undef SEARCH
#define SEARCH(x) {#x, search_##x},
std::map<std::string, search> search_funcs = {
#include "search_func.incl"
};
#undef SEARCH
int main(char** argv, int argc)
{
std::cout << search_funcs["esa"](1, 2) << std::endl;
std::cout << search_funcs["tss"](3, 4) << std::endl;
std::cout << search_funcs["fss"](5, 6) << std::endl;
std::cout << search_funcs["ds"](7, 8) << std::endl;
return 0;
}
int search_esa(int a, int b) { return 100 * a + 10 * b + 0; }
int search_tss(int a, int b) { return 100 * a + 10 * b + 1; }
int search_fss(int a, int b) { return 100 * a + 10 * b + 2; }
int search_ds(int a, int b) { return 100 * a + 10 * b + 3; }
In search_func.incl
SEARCH(esa)
SEARCH(tss)
SEARCH(fss)
SEARCH(ds)
How this works The search_func.incl file specifies the name of your search functions with a macro. When you include the file, you switch up the definition of the macro so that the included functions are presented differently.
SEARCH(abc)
becomes a function declaration on the first include:
int search_abc(int a, int b);
and a key value pair {string, function pointer} on the second include:
{"abc", search_abc},
These KVP are in a map, so when you need to call a function, the string maps to the function name automatically.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments