Pointers and recursive templates
Submitted by bwy on Wed, 02.09.2009 - 07:18
How do you get the 'pointed-to' type in C++?
template<typename T> struct RemovePointer { typedef T value_type; }; template<typename T> struct RemovePointer<T*> { typedef typename RemovePointer<T>::value_type value_type; };
What's the point? With a bit of boost magic, you can use pointers transparently in generic code:
#include <boost/bind.hpp> #include <vector> #include <list> #include <algorithm> struct Foo { void f() const {} }; template<typename T> void doAll(const T& container) { typedef typename RemovePointer<typename T::value_type>::value_type contained_type; std::for_each(container.begin(), container.end(), boost::mem_fn(&contained_type::f)); } int main() { std::vector<Foo*> fooPointers(4, new Foo); std::list<Foo> foos(4); doAll(fooPointers); doAll(foos); }
Now the generic function template doAll can be called on a container of Foos and a container of pointers to Foos, calling Foo::f() for each element.
Calling doAll for a container of pointers to pointers to Foos - such as std::vector<Foo**>
- will cause a compile failure in boost::mem_fn.