Short Version:
The main point is that the (complex) state of an instance can be changed by functions that are outside the definition of the class, as such the class can be extended to have all sorts of internal states without polluting the class defintion with many state-setters.
Assume the following code:
class bar
{
virtual void ChangeState()=0;
}
class foo:bar
{
private:
int b;
public:
void ChangeState() {b=3;}
}
What I would like to do is create different functions, then pass them to the function, at runtime, something like
foo.ChangeState(); //b is 3 now
void foo::(?)ChangeState2(){ b=2; };
foo.ChangeState=ChangeState2;
foo.ChangeState(); //b is 2 now
Can such a construct be implemented in C++, without the use of hacks?
Maybe, this will help:
#include <iostream>
namespace so
{
class B
{
friend void change_1( B * );
friend void change_2( B * );
friend void change_3( B * );
int i;
public:
B() : i{ 0 } {}
void change_state( void (*_function)( B * ) )
{
_function( this );
std::cout << i << std::endl;
}
};
void change_1( B * _object )
{
_object->i = -1;
}
void change_2( B * _object )
{
_object->i = -2;
}
void change_3( B * _object )
{
_object->i = -3;
}
} //namespace so
int main()
{
so::B b{ };
b.change_state( so::change_1 );
b.change_state( so::change_2 );
b.change_state( so::change_3 );
return( 0 );
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With