Neverlord/libcppa — Issue #10: Add a bit of type safety to message handling
Author: mephi42
Created: 2011-10-12 11:57:04+00:00
State: open

I've always been nervous about having to duplicate knowledge about atom value and message parameter types on sending (cppa::send) and receiving (cppa::on) ends, which might cause trouble when some of them change and are not properly updated.

I wrote a helper class that helps consolidating this knowledge in one place and I'm wondering if something similar could be added to the library.

Here is the code:

```c++
#include
#include

#include

#include

#define MESSAGE_ON_TEMPLATE_ELEMENT(z, n, unused) , typename T##n
#define MESSAGE_ON_TEMPLATE(n) template

#define MESSAGE_ON_ARGUMENT(z, n, unused) , cppa::val()
#define MESSAGE_ON_RETVAL(n) cppa::on(id BOOST_PP_REPEAT_FROM_TO(1, BOOST_PP_ADD(1, n), MESSAGE_ON_ARGUMENT, nil))

#define MESSAGE_ON(z, n, unused) \
MESSAGE_ON_TEMPLATE(n) \
auto message_on(cppa::atom_value id) -> decltype(MESSAGE_ON_RETVAL(n)) { \
return MESSAGE_ON_RETVAL(n); \
}

BOOST_PP_REPEAT_FROM_TO(1, 23, MESSAGE_ON, nil)

template
class message {
public:
static void send(cppa::actor_ptr actor, Args... args) {
cppa::send(actor, M::id, args...);
}

static decltype(message_on(M::id)) on() {
return message_on(M::id);
}
};

class hello_id {
public:
static const cppa::atom_value id;
};
const cppa::atom_value hello_id::id = cppa::atom("hello");
class hello : public message {
};

int main() {
hello::send(cppa::self(), "world");
cppa::receive(hello::on() >> [](const std::string s) {
std::cout << "hello " << s << std::endl;
});
return 0;
}
```