【问题标题】:How to loop through a boost::mpl::list?如何循环通过 boost::mpl::list?
【发布时间】:2011-02-19 21:41:12
【问题描述】:

这是我所知道的,

#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,只是基于此处另一个答案的猜测)

【问题讨论】:

    标签: c++ templates boost metaprogramming boost-mpl


    【解决方案1】:

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

    【讨论】:

    • 谢谢 - 有没有办法使用 boost::bind 而不是包装对象来做到这一点?
    • @Kyle:我不这么认为 - 我不知道 Boost.Bind 中有任何实用程序可以使用模板化的operator() 生成所需的函子。
    • @GeorgFritzsche:有没有办法让do_this_wrapper 成为 lambda(从 C++11/14/17 开始)?
    • @AdiShavit 这应该可以用 C++14s generic lambdas.
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多