almost the equal objects

I need make the vector from the objects type
1
2
3
4
5
class My_class
{
    int x;
    void fn_x(int x);
}

but for each object fn_x is diffirent
1
2
3
4
5
6
7
8
void fn_1(int x)
{
    x += 1;
}
void fn_2(int x)
{
    x -= 5;
}

etc. I will add variable "string name" and use this as name of function. But this code is not portable. After I will make the function
1
2
3
4
5
6
void fn(string name, int x)
{
    if (name=="fn_1") { fn_1(x); }
    else if (name=="fn_2") { fn_2(x); }
    // etc
}

I do not like because the functions are inserted, and I must define in class all functions, one use.
Can anyone advise better?
I think that it would be better if you use inheritance and virtual functions.
thank
I presume this is a simplified example, otherwise simply storing the amount you want to increment or decrement x and applying that would be the simplest thing to do.

Here's an alternative:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <functional>
#include <iostream>

class C
{
public:
    C( std::function<void(int&)> f ) : _fn(f), x(0) {}

    int get() const { return x ; }
    
    void applyFn() { _fn(x) ; }

private:
    std::function<void(int&)> _fn ;
    int x ;
};

void increment_by_1(int& x)
{
    ++x ;
}

void decrement_by_5(int& x )
{
    x-=5 ;
}

int main()
{
    C c1(increment_by_1) ;
    C c2(decrement_by_5) ;

    for ( unsigned i=0 ; i < 10 ; ++i )
    {
        c1.applyFn() ;
        c2.applyFn() ;
    }

    std::cout << "c1: " << c1.get() 
              << "\nc2: " << c2.get() << '\n' ;
}
Topic archived. No new replies allowed.