我如何迭代元组

时间:2010-12-26 02:42:39

标签: c++ boost

如何从索引1到2开始迭代元组?以下不起作用。

using boost::fusion::cons;
typedef cons<A, cons<B, cons<C, cons<D> > > > MyTuple;
MyTuple tuple_;

template <class 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_) );

2 个答案:

答案 0 :(得分:1)

我不确定您的意图,但以下代码是否符合您的目的? 我使用fusion而不是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() );    

希望这有帮助

答案 1 :(得分:0)

从你的评论来看, 你提到的可能是通过制作一个谓词来实现的 确定指定类是否具有成员函数的类, 并使用fusion::filter_view。 以下代码中的DEF_HAS_MEM_FUNC宏在以下位置进行了解释:

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() );
}