Boost logo

Boost :

From: Peter Dimov (pdimov_at_[hidden])
Date: 2002-04-22 04:59:38


The best I can do is:

template<class L, class F> void visit(boost::any * p, F f);

int main()
{
    typedef list<int, double, std::string>::type L;
    boost::any a = std::string("test.");
    visit<L>(&a, std::cout << boost::lambda::_1 << '\n');
}

Complete program (does not require partial specialization except for the
lambda part):

#include <boost/any.hpp>

class missing;
class nil;

template<class F, class R> struct pair
{
    typedef F first;
    typedef R rest;
};

template<class A1 = missing, class A2 = missing, class A3 = missing, class
A4 = missing> struct list
{
    typedef pair<A1, typename list<A2, A3, A4, missing>::type> type;
};

template<> struct list<missing, missing, missing, missing>
{
    typedef nil type;
};

template<class L> struct visit_helper
{
    template<class F> void operator()(boost::any * p, F f)
    {
        typedef typename L::first first;
        typedef typename L::rest rest;

        if(first * pf = boost::any_cast<first>(p))
        {
            f(*pf);
        }

        visit_helper<rest>()(p, f);
    }
};

template<> struct visit_helper<nil>
{
    template<class F> void operator()(boost::any *, F)
    {
    }
};

template<class L, class F> void visit(boost::any * p, F f)
{
    visit_helper<L>()(p, f);
}

#include <boost/lambda/lambda.hpp>
#include <iostream>
#include <string>

int main()
{
    typedef list<int, double, std::string>::type L;
    boost::any a = std::string("test.");
    visit<L>(&a, std::cout << boost::lambda::_1 << '\n');
}


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk