In my last posting about C++ Multiple Dispatch I wondered if it was really any different than function overloading. I now appreciate that it is something that needs to occur at runtime, not compile time. With a little help from the Boost libraries, I threw together this example of how one could do Multiple Dispatch in C++.
If boost::threads represent the C of multithreaded programming, then RAII and automatically managed threads represent the C++ of multithreaded programming.
In the last article we promised that using more RAII would allow us to get this code even smaller and better to manage. Here is the result of that:
class threaded_class
{
public:
threaded_class()
: m_stoprequested(false),
m_thread(boost::bind(&threaded_class::do_work, this)) //Note 2
{
}
~threaded_class()
{
If pthreads represent the assembly language of multithreading programming, then boost::threads represent the C of multithreaded programming.
Boost threads introduce some handy code saving features for the creation of threads, which is nice, but not as important as the RAII techniques they put to use for mutex management. In this case an example is worth a thousand words. Here is the same code we wrote in for pthreads rewritten for boost::threads:
class threaded_class
{
public:
threaded_class()
Say you come up with a clever idea for initializing standard container types (blatantly stolen from the C++0x Initializer List concept). It might looks something like the implementation below:
#include <vector>
using namespace std;
template<template<typename DT> class container, typename DT>
container<DT> initializer(const DT &d)
{
container<DT> t;
t.insert(t.end(), d);
return t;
}
int main(int, char *[])
{
vector<int> v = initializer<vector>(5);
}But that only works for 1 parameter! Let's add a second one:
#include
The boost spirit library allows for direct translation of a BNF grammar into C++ code which generates a parser at compile time. The following example, from http://spirit.sourceforge.net/distrib/spirit_1_8_3/libs/spirit/doc/introduction.html truly does this concept more justice than I could:
BNF Example:
group ::= '(' expression ')'
factor ::= integer | group
term ::= factor (('*' factor) | ('/' factor))*
expression ::= term (('+' term) | ('-' term))*boost contains a preprocessor metaprogramming libary. What this means, simply, is that it is possible to write code which generates code. The full docs are here.
It is possible to do full LISP-like lambda calculus with the library. That's not, however, where my interests lie. For me, the practical use is to automatically generate a set of templates which take N arguments and let the compiler generate all of the N iterations for you.
Recent comments
3 days 20 hours ago
3 days 22 hours ago
3 days 22 hours ago
6 days 23 hours ago
1 week 5 min ago
1 week 3 days ago
2 weeks 3 days ago
5 weeks 3 days ago
7 weeks 55 min ago
8 weeks 2 days ago