How do I iterate over a tuple
How can I iterate over a tuple starting from, say, index 1 to 2? The following doesn't work.
using boost::fusion::cons;
typedef cons<A, cons<B, cons<C, cons<D> > > > MyTuple;
MyTuple tuple_;
template <class开发者_JS百科 T>
struct DoSomething{
DoSomething(T& t) : t_(&t){ }
template <class U>
void operator()(U u){
boost::fusion::at<mpl::int_<u> >(*t_);
}
T* t_;
};
boost::mpl::for_each< boost::mpl::range_c<int, 1, 3> >( DoSomething<MyTuple>(tuple_) );
I'm not sure about your intent, but will the following code serve your purpose?
I used fusion
all over instead of mpl
.
struct DoSomething {
template< class U >
void operator()( U u ) const {
std::cout << u << '\n'; // an example
}
};
using namespace boost::fusion; // Sorry, for brevity
iterator_range<
result_of::advance_c< result_of::begin< MyTuple >::type, 1 >::type
, result_of::advance_c< result_of::begin< MyTuple >::type, 3 >::type
> ir( advance_c< 1 >( begin( tuple_ ) )
, advance_c< 3 >( begin( tuple_ ) ) );
for_each( ir, DoSomething() );
Hope this helps
Judging from your comment,
what you mentioned can be implemented probably by making a predicate
class which determines whether the specified class has the member function,
and using fusion::filter_view
.
DEF_HAS_MEM_FUNC
macro in the following code is explained at:
Is it possible to write a template to check for a function's existence?
#include <boost/fusion/include/cons.hpp>
#include <boost/fusion/include/filter_view.hpp>
#include <boost/fusion/include/for_each.hpp>
#include <boost/mpl/placeholders.hpp>
using namespace boost;
#define DEF_HAS_MEM_FUNC( name, func_name, signature ) \
template< class T > \
struct name { \
template< class U, U > struct mfp; \
\
template< class U > \
static char f( mfp< signature, &U::func_name >* ); \
\
template< class > static char (&f(...))[2]; \
\
enum { value = (sizeof( f<T>(0) ) == 1) }; \
}
DEF_HAS_MEM_FUNC( has_f, f, void(U::*)()const );
struct DoSomething {
template< class U >
void operator()( U& u ) const {
u.f();
}
};
struct A {};
struct B {
void f() const {}
};
typedef fusion::cons< A, fusion::cons< B > > MyTuple;
int main()
{
MyTuple tuple_;
fusion::filter_view< MyTuple const, has_f< mpl::_ > > v( tuple_ );
fusion::for_each( v, DoSomething() );
}
精彩评论