Here is the question:
I want to call some functions that are the same type and use a variable or a property to selects these functions.
At sometimes, I can use the switch struct to do it. But sometimes, I can not! For example: the type of the variable
is a string(like this: switch ("mystring") { ... }
).
In this case, I think you can try the map function to do it.
At first, We need to define some types:
typedef float optfunc_t(float a, float b);
typedef std::map<std::string, optfunc_t*> strfmap_t;
As you seeing, The optfunc_t
is type of our functions and We can call these functions by a variable that type of strfmap_t
:
float plus(float a, float b)
{
return a + b;
}
float minus(float a, float b)
{
return a - b;
}
int main()
{
strfmap_t m;
m["plus"] = plus;
m["minus"] = minus;
std::cout << m["plus"](100.01, 10.001) << std::endl;
std::cout << m["minus"](100.01, 10.001) << std::endl;
return 0;
}
In the above code. We create a variable m
and set two pairs of string and function. These operations are very simple. Let us to call it.
Here is the fully code:
#include <iostream>
#include <map>
#include <string>
typedef float optfunc_t(float a, float b);
typedef std::map<std::string, optfunc_t*> strfmap_t;
float plus(float a, float b)
{
return a + b;
}
float minus(float a, float b)
{
return a - b;
}
int main()
{
strfmap_t m;
m["plus"] = plus;
m["minus"] = minus;
std::cout << m["plus"](100.01, 10.001) << std::endl;
std::cout << m["minus"](100.01, 10.001) << std::endl;
return 0;
}
原创文章,作者:KK,如若转载,请注明出处:https://www.zfjsec.com/184.html