| C++ template metaprogramming, exercise 2-1 |
[09 Mar 2007|08:45am] |
Ok so I flipped this book open when I was bored at work yesterday and did the first exercise: write a unary metafunction add_const_ref<T> that returns T if T is a reference type, or T const& if it's not. The solution was three small structs as per some guidelines in chapter one. "This metafunction stuff is a piece of piss," I thought.
Turned to exercise two: write a ternary metafunction replace_type<C, X, Y> that takes an arbitrary compound type C as its first parameter, and replaces all occurrences of a type X within C with Y.
I had no idea how to do it - thought about approaching it with some crazy recursive template specialisations that strip C of its qualifiers (*, const, & etc.), replace the underlying types, and put it all back together - but I was basically stuck.
There's a solution here, but it seems rather ugly. Sure enough, it's about a page and a half of template specialisations for different compound types.
Just wondering if others had explored this area, and whether it's really worth writing this type of code if you're not a library designer - i.e. to solve practical problems. Anyone using it extensively in their professional lives?
|
|