Skip to content

Instantly share code, notes, and snippets.

@qsorix
Created February 1, 2013 21:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save qsorix/4694297 to your computer and use it in GitHub Desktop.
Save qsorix/4694297 to your computer and use it in GitHub Desktop.
Playing with C++11 lambdas to get erlang-like receive statement.
#include <iostream>
#include <vector>
#include <functional>
enum message_type {PING, PONG};
struct Message {
message_type m_type;
Message(message_type t) : m_type(t) {}
message_type type() const { return m_type; }
};
std::function<bool(Message)> t(message_type expected)
{
return [=](Message m) {return m.type() == expected;};
}
typedef size_t timedef;
typedef std::function<bool(Message)> filter;
typedef std::function<void(Message)> handler;
typedef std::function<void(void)> timeout_handler;
typedef std::pair<filter, handler> handler_def;
typedef std::pair<timedef, timeout_handler> timeout_def;
typedef std::pair<std::vector<handler_def>, std::vector<timeout_def>> handlers;
void receive(handlers h)
{
// todo: go over h.second and register timeouts
// now pretend we've received a message, see if any handler is
// interested in it and handle accordingly
Message m(PING);
for (const std::pair<filter, handler>& p : h.first)
{
if(p.first(m))
{
p.second(m);
break;
}
}
}
// -----------------------------------------------------------------------------
int main()
{
receive(
{{
{t(PING), [](Message m)
{
std::cout << "I got PING: " << m.type() << std::endl;
}},
{t(PONG), [](Message m)
{
std::cout << "I got PONG: " << m.type() << std::endl;
}}
},{
{100, []()
{
std::cout << "timeout" << std::endl;
}}
}});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment