Reputation: 503
I want to make a struct that can be initialized so that without using if or switch statements, the struct shows the function that the user have chosen at the beginning. Similar to readonly
in C#.
So after declaring a struct S
, containing a function f()
, for example, f()
should work different if I declare the structure as S("a")
or S("b")
.
Upvotes: 1
Views: 103
Reputation: 63152
Yes
You can use a function pointer, or other callable object. You can put those things in a map, and lookup in the map when you construct an S
void f_A() { std::cout << "called a"; }
void f_B() { std::cout << "called b"; }
std::map<std::string, void(*)()> functions = { { "a", f_A }, { "b", f_B } };
struct S
{
S(std::string id) : f(functions[id]) {}
void(*f)();
}
int main()
{
S a("a");
S b("b");
a.f();
b.f();
return 0;
}
If you need S
to have other state, and the f
s to use it, you can modify the example thus:
struct S; // need to forward declare S
void f_A(S* s) { std::cout << "called a with " << s->foo; }
void f_B(S* s) { std::cout << "called b with " << 2 * s->foo; }
std::map<std::string, void(*)(S*)> functions = { { "a", f_A }, { "b", f_B } };
struct S
{
S(std::string id, int foo_) : f_impl(functions[id]), foo(foo_) {}
void f() { f_impl(this); }
int foo;
private:
void (*f_impl)(S*);
}
Upvotes: 4