This is aspect-oriented example.
Create a factory.h file :
Code:
/*This is a file factory.h */
typedef bool (*funcPtr)(int , int);
#include <map>
class OperatorsFactory
{
private:
//Did not have time for generic singleton :)
/ nor generic factory :)
OperatorsFactory() {}
~OperatorsFactory() {}
std::map< char, funcPtr > operationsMap;
public:
OperatorsFactory& getInstance()
{
static OperatorsFactory of;
return of
}
void register( char op , funcPtr fp )
{
operationsMap.insert ( make_pair( op , fp ) );
}
funcPtr getByOperator( char op )
{
return operationsMap.find( op.second );
}
}
//--------------End of Factory.h -----------------------------------///
Next , create a file called less_than.cpp and add it to project
Code:
/*This is less_than.cpp */
#include "factory.h"
//Anonymous namespace , common practise , for this things , I'll explain why some other time :)
namespace
{
bool less_than_function( int a , int b )
{
return a < b;
}
OperatorsFactory::getInstance().register( '<' , less_than_function);
}
Create main.cpp , and add it to project :
Code:
/*This is less_than.cpp */
//Note the fact I did NOT use #include less_than.h or anything !
#include "factory.h"
int main()
{
char c;
cin >>c ;
OperatorsFactory& opFactory = OperatorsFactory::getInstance().
funcPtr fp = opFactory.getByOperator(c);
if(fp(2,3))
cout << "Yes! it\'s alive! " << endl;
}
//--------------End of main.cpp -----------------------------------///
Now here's the interesting part
If you wany yo create another operator, create a file called , for example , equals.cpp
and add it to project
Code:
/*This is l equals.cpp */
#include "factory.h"
//Anonymous namespace , common practise , for this things , I'll explain why some other time :)
namespace
{
bool equals( int a , int b )
{
return a < b;
}
OperatorsFactory::getInstance().register( '==' , equals);
}
//--------------End of equals.cpp -----------------------------------///
Now, if you want to use operator '==' , you don't have to change main.cpp file,
just add equals.cpp to project, and it'll self-register the '==' operator to main.cpp
You can do this for as many operators as you would like.
Of course, you can put as many operators as you want in one cpp file.
Of course, this aspect-oriented example is used for some larger projects , which need this plugin-based architecture,
this is a little bit of over-kill .
The whole strength in this example is that you don't change your main.cpp code.
When you want a new operator , you add a new module ( you add the code , you don't change it )
It also has an advantage of code being a lot less coupled, unlike switch statement, which has to #include all
the code in one file. Less external depencies makes program a lot easier to maintain .
Btw, did I've scared you with this code ? You've asked for dynamic operators , and I've thrown you the aspect-oriented programming
Sorry if I did
Cheers!
Bookmarks