|
Boost Users : |
From: Geoffrey Irving (irving_at_[hidden])
Date: 2005-08-27 17:19:51
Thanks! I knew something like could be written, but for some reason I thought
there'd be significantly more overhead in turning a function into something
loopable.
It's unfortunate that one can't pass a function template as a template argument,
since that would remove the need for the extra functor class entirely.
Geoffrey
On Fri, Aug 26, 2005 at 04:24:36PM -0500, Alan M. Carroll wrote:
> Here's some code I whipped out that does what you want, although I'm sure it
> could be done better (it was an interesting learning exercise, though)
>
> # include <boost/mpl/if.hpp>
> # include <boost/mpl/list.hpp>
> # include <boost/mpl/empty.hpp>
> # include <boost/mpl/front.hpp>
> # include <boost/mpl/pop_front.hpp>
>
> // this is the thing we want to call on the types
> // We don't put it in the functor so that it can be specialized in multiple
> places
> template < typename T > void complicated_function( int i) {
> std::cout << "i = " << i << " sizeof = " << sizeof (T) << std::endl;
> }
>
> // need this as a simple type so we can pass it to chain
> struct functor {
> template < typename T > void operator () (int i) const {
> complicated_function<T>(i); }
> };
>
> // do tail recursion on L using the functor F
> template < typename F , typename L > struct chain {
> struct tail { void operator () (int i) const { return ; } };
> struct main {
> void operator () (int i) const {
> F f;
> f. operator ()<boost::mpl::front<L>::type >(i);
> chain<F, boost::mpl::pop_front<L>::type>()(i);
> }
> };
> void operator () (int i) const {
> boost::mpl::if_c<boost::mpl::empty<L>::value,
> tail, main
> >::type ()(i);
> }
> };
>
> // A list of types to use
> typedef boost::mpl::list< int, double , char , std::string> the_list;
>
> // demonstrate that we're calling complicated_function for each type in the
> list
> void mpl_test() {
> chain<functor, the_list>()(17);
> }
Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net