user5876164
user5876164

Reputation: 503

How can I make a struct with a function that can be changed in c++?

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").

  1. Is it possible?
  2. If it is, how?

Upvotes: 1

Views: 103

Answers (1)

Caleth
Caleth

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 fs 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

Related Questions