Reputation: 496
So working with a bunch of if statements, I'm thinking someone can help me out with a better way.
Here is what I'm trying to do. Say I have 3 strings, I want to assign that string a function if that string is found...
Currently a basic example of what I'm doing:
if(findStr(string1)) {
function1(perams);
}
else if (findStr(string2)) {
function2(perams);
}
else if (findStr(string3)) {
function3(perams);
}
I am doing something similar on a larger scale, 10 different strings and each string corresponds to it's own function.
I am open to options that involve maybe a structure for my strings?
I would like to just do one if statement, even if a loop is involved. I don't want to have to call "function1", "function2", "function3" I want it to somehow be associated with the string.
Is this possible to do cleanly? or are the if statements the cleanest way to do this?
Thanks guys
Upvotes: 0
Views: 231
Reputation: 29764
You can use a map of strings associated with pointers to function, i.e:
In case of class members:
typedef void (MyClass::*f)( peramsType);
typedef map< std::string, f> MyMap;
usage
MyClass t;
f f_ptr = myMap["string1"];
( t.*f_ptr)( perams); // -> call function pointed by f_ptr through t object
In case of non-class members:
typedef void (*f)( peramsType);
typedef map< std::string, f> MyMap;
usage:
f f_ptr = myMap["string1"];
( *f_ptr)( perams); // -> call non-class function pointed by f_ptr
Good practice is to derive from std::function, so you can write it like:
#include <functional>
typedef std::function< void( peramsType)> f;
std::map < std::string, f> MyMap;
Upvotes: 6
Reputation: 23041
In C++11 you can do this:
#include <functional>
#include <map>
#include <string>
typedef std::function<void(PARAMS)> func_t;
typedef std::map<std::string,func_t> map_t;
where PARAMS is a list of your function parameters. For example std::function<void(int,float)>
would indicate a function which takes two parameters, an int
and a float
.
See here for more information about std::function
.
Upvotes: 1
Reputation: 55425
You can map the strings to functions pointers, check if the string is in the map and then call it. Something like this:
typedef void(*Func)();
void foo1();
void foo2();
void foo3();
std::map<std::string, Func> m =
{ {"first", foo1}, {"second", foo2}, {"third", foo3} };
std::string str = "first";
auto it = m.find(str);
if (it != m.end()) (it->second)();
Upvotes: 1
Reputation: 11058
You might want to use an array of pairs (string, function pointer), something like:
struct {
string s;
void (*f)(Params p);
} my_map[] = { { string1, function1}, {string2, function2} };
for (int i = 0; i < 2; i++) {
if (findStr(my_map[i].s)) {
my_map[i].f(perams);
break;
}
}
Upvotes: 1