2010-05-15 93 views
9

這是據我已經得到了,如何通過boost :: mpl :: list循環?

#include <boost/mpl/list.hpp> 
#include <algorithm> 
namespace mpl = boost::mpl; 

class RunAround {}; 
class HopUpAndDown {}; 
class Sleep {}; 

template<typename Instructions> int doThis(); 
template<> int doThis<RunAround>() { /* run run run.. */ return 3; } 
template<> int doThis<HopUpAndDown>() { /* hop hop hop.. */ return 2; } 
template<> int doThis<Sleep>()  { /* zzz.. */ return -2; } 


int main() 
{ 
    typedef mpl::list<RunAround, HopUpAndDown, Sleep> acts; 

// std::for_each(mpl::begin<acts>::type, mpl::end<acts>::type, doThis<????>); 

    return 0; 
}; 

如何完成呢? (我不知道我是否應該使用std :: for_each,只是根據另一個答案在這裏猜測)

回答

13

使用mpl::for_each在類型列表上進行運行時迭代。例如:

struct do_this_wrapper { 
    template<typename U> void operator()(U) { 
     doThis<U>(); 
    } 
}; 

int main() { 
    typedef boost::mpl::list<RunAround, HopUpAndDown, Sleep> acts; 
    boost::mpl::for_each<acts>(do_this_wrapper());  
}; 
+1

謝謝 - 有沒有辦法使用boost :: bind來代替wrapper對象? – Kyle 2010-05-15 15:46:59

+2

@Kyle:我不這麼認爲 - 我沒有意識到Boost.Bind中的任何實用工具都會生成一個模板化的'operator()'所需的函子。 – 2010-05-15 15:53:19

+0

@GeorgFritzsche:有沒有辦法讓'do_this_wrapper'成爲一個lambda(從C++ 11/14/17開始)? – 2016-09-05 12:27:47