簡體   English   中英

我如何遍歷元組

[英]How do I iterate over a tuple

我如何遍歷從索引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_) );

我不確定您的意圖,但是以下代碼是否可以滿足您的目的? 我使用了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() );    

希望這可以幫助

從您的評論來看,可以通過創建一個謂詞類來實現您提到的內容,該謂詞類確定指定的類是否具有成員函數,並使用fusion::filter_view 以下代碼中的DEF_HAS_MEM_FUNC宏說明:

是否可以編寫模板來檢查函數的存在?

#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