简体   繁体   English

我如何遍历元组

[英]How do I iterate over a tuple

How can I iterate over a tuple starting from, say, index 1 to 2? 我如何遍历从索引1到2的元组? The following doesn't work. 以下无效。

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

I'm not sure about your intent, but will the following code serve your purpose? 我不确定您的意图,但是以下代码是否可以满足您的目的? I used fusion all over instead of mpl . 我使用了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() );    

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 . 从您的评论来看,可以通过创建一个谓词类来实现您提到的内容,该谓词类确定指定的类是否具有成员函数,并使用fusion::filter_view DEF_HAS_MEM_FUNC macro in the following code is explained at: 以下代码中的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() );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM