ntroductionSometimes it is useful to have dynamic message passing as in Objective-C. The small header presented below allows any class to contain a dynamic message map that can be used to add methods dynamically to an object. BackgroundObjective-C is deemed more flexible than C++ because it allows a form of dynamic dispatch known as message passing.Message passing is a form of dynamic dispatch that does not require implementation of a specific interface type. When sending a message to a target object, it is unknown to the compiler if the message can be handled by the object or not. It is only during the execution of the program that conformance to an interface is discovered. Message passing is quite flexible because it does not require a lot of planning. Objective-C has been praised for this feature as more flexible than C++. This article demonstrates how easy it is to do the same in standard C++ (c++0x). Using the code Using the code is very easy. The following steps have to be followed:
#include "mp_object.hpp"
using namespace std;//prototype method
void draw() {}//prototype method
void setColor(int color) {}//rectangle
class rect : public mp_object {
public:
//constructor
rect() {
add_method(::draw, &rect::draw);
add_method(::setColor, &rect::setColor);
} //draw
void draw() {
cout << "rect\n";
} //set color
void setColor(int color) {
cout << "rect color = " << color << "\n";
}
};//circle
class circle : public mp_object {
Read more: Codeproject
- include the header "mp_object.hpp" in your project.
- inherit from class mp_object.
- add dynamic methods to your object by using the method 'add_method'.
#include "mp_object.hpp"
using namespace std;//prototype method
void draw() {}//prototype method
void setColor(int color) {}//rectangle
class rect : public mp_object {
public:
//constructor
rect() {
add_method(::draw, &rect::draw);
add_method(::setColor, &rect::setColor);
} //draw
void draw() {
cout << "rect\n";
} //set color
void setColor(int color) {
cout << "rect color = " << color << "\n";
}
};//circle
class circle : public mp_object {
Read more: Codeproject
0 comments:
Post a Comment