Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the behaviour of a method at runtime?

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?

like image 222
Taikand Avatar asked Aug 21 '13 19:08

Taikand


1 Answers

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 );
}
like image 107
lapk Avatar answered Nov 09 '22 23:11

lapk