Introduction
Programming languages like Smalltalk and Objective-C are considered more flexible than C++ because they support dynamic message passing. C++ does not support dynamic message passing; it only supports static message passing: when a method of an object is invoked, the target object must have the invoked method; otherwise, the compiler outputs an error.
Although the way C++ does message passing is much faster than the way Smalltalk or Objective-C does it, sometimes the flexibility of Smalltalk or Objective-C is required. This little article shows how it is possible to achieve dynamic message passing in C++ with minimum code.
Background
C++ achieves message passing with the help of vtables.
Smalltalk and Objective C use a method map to achieve the same result.
Example
The supplied header contains an implementation of dynamic message passing. In order to add dynamic message passing capabilities to an object, the following things must be done:
- Declare a global function which acts as a signature of the message.
- Inherit from
dmp::object
. - In the class constructor, add one or more messages to the object using the method
add_message
. - Send a message to an object using the function
invoke(signature, ...parameters)
.
Here is an example:
#include "dmp.hpp"
std::string my_message(int a, double b) { return ""; }
class test : public dmp::object {
public:
test() {
add_message(&::my_message, &test::my_message);
}
std::string my_message(int a, double b);
};
int main() {
test t;
std::string s = t.invoke(&::my_message, 10, 3.14);
}
How it Works
Each object contains a shared ptr to a map. The map's key is the pointer to the signature of the message. The map's value is a pointer to an internal message structure which holds a pointer to the method to invoke.
When a method is invoked, the appropriate message structure is retrieved from the map, and the method of the object stored in the message structure is invoked, using this
as the target object.
The map used internally is unordered, for efficiency reasons.
The message map of objects is shared between objects for efficiency reasons as well. When a message map is modified, it is duplicated if it is not unique, i.e., the copy-on-write pattern is applied.
The code is thread safe only when the message maps are not modified while used for look-up by different threads. If a message map is modified, then no thread must send messages to an object at the same time.
The code uses the boost library because of:
- unordered maps; the class
boost::unordered_map
is used. - the pre-processor; used for automatically constructing code for different number of parameters.
- shared ptrs; used for internal memory management.