In a recent post I admired the functional programming features (among many other features) that the BOOST libraries add to the C++ runtime system. Well guess what there is a pure, lazy functional programming language looming in C++'s template system! That means all the features you know and love from Haskell.
I've been reading "C++ Template Metaprogramming: Concepts, Tools, and Techniques from Boost and Beyond". It outlines how can make use of metaprogramming features in your programs.
A Simple Example
This is an introductory example from the book. Let's say you want to conveniently express binary numbers in your code. You could write a conversion function like this:
/*
* general case
*/
template<unsigned long N>
struct binary
I've been reading "C++ Template Metaprogramming: Concepts, Tools, and Techniques from Boost and Beyond". It outlines how can make use of metaprogramming features in your programs.
A Simple Example
This is an introductory example from the book. Let's say you want to conveniently express binary numbers in your code. You could write a conversion function like this:
/*
* general case
*/
template<unsigned long N>
struct binary
{
static unsigned const value =
binary::value <N/10> * 2 + N%10;
}
/*
* special case, invoked to terminate recursion
*/
template<>
struct binary<0>
{
static unsigned const value = 0;
}
static unsigned const value =
binary
}
/*
* special case, invoked to terminate recursion
*/
template<>
struct binary<0>
{
static unsigned const value = 0;
}
In your code you could then write something like the following
/*
* the binary expression is converted to 42 at compile time
*/
int fortytwo = binary<101010>::value;
If you're familiar with functional programming this should look familiar to you. And even if you don't know FP, the example shouldn't be too complicated to grasp. When a binary expression is compiled, the general binary struct is invoked recursively until the remainder is zero, at which point the so called template specialization is called which terminates the recursion.
Even from this simple example I think you can see potential uses Metaprogramming, especially when it comes to crafting domain specific languages for your application. The book dedicates a whole chapter to the design of domain specific embedded languages.
BOOST Support
BOOST also provides the metaprogramming library (mpl), which is a template metaprogramming framework of compile-time algorithms, sequences and metafunctions. mpl is also extensively used in the book. Another objective of the mpl is reduce the syntactic noise the templates produce. Template syntax is becoming really messy really quickly if expressions grow just little complex.
No comments:
Post a Comment