【问题标题】:How can I check if a type is mpl::apply-able?如何检查类型是否为 mpl::apply-able?
【发布时间】:2013-08-30 21:21:46
【问题描述】:

如果我有一个类型,T,看起来像Foo<mpl::_1>,我可以通过mpl::apply<T, int>::type 得到Foo<int>

但如果T 是一个完整的类型,比如Foo<int>,那么mpl::apply<T, int>::type 将无法编译。

我想编写一个元函数,如果可能,它将应用一个类型,否则返回该类型。所以像:

template <typename Partial, typename T>
struct maybe_apply
: eval_if_c<??????,
    mpl::apply<Partial, T>,
    mpl::identity<Partial>>
{ };

我可以在 ???s 中添加什么,这样才能达到我想要的效果?

【问题讨论】:

    标签: c++ boost-mpl


    【解决方案1】:

    免责声明:我远不是 MPL 方面的专家,所以我不能保证这是解决这个问题的最佳方法(或者即使它是正确的,它似乎至少可以工作)。

    根据文档,mpl::apply 的第一个参数/参数必须是 Lambda 表达式,并且可以是元函数类或占位符表达式。一个快速的谷歌搜索把我带到了this post。根据该帖子,mpl::is_lambda_expression 允许您确定类型是否为占位符表达式。在 Boost.TTI(即从 1.54 版开始的 boost)中,您可以找到一个完全符合您要求的元函数。这个元函数是boost::tti::detail::is_lambda_expression,可以在boost/tti/detail/dlambda.hpp 中找到。在下面的示例中,我使用了与 TTI 用于查找类型是否为元函数类的完全相同的宏。

    Running on Coliru.

    #include <iostream>
    #include <typeinfo>
    
    #include <boost/utility.hpp>
    
    #include <boost/mpl/apply.hpp>
    #include <boost/mpl/eval_if.hpp>
    #include <boost/mpl/identity.hpp>
    
    #include <boost/mpl/plus.hpp>
    
    namespace mpl=boost::mpl;
    
    
    /* //This is another way to do it
    template <typename T, typename Enable=void>
    struct is_apply_able : mpl::false_
    {};
    
    template <typename T>
    struct is_apply_able<T,typename boost::enable_if<mpl::is_lambda_expression<T> >::type> : mpl::true_
    {};
    BOOST_MPL_HAS_XXX_TEMPLATE_NAMED_DEF(is_metafunction_class, apply, false)
    template <typename T>
    struct is_apply_able<T,typename boost::enable_if<is_metafunction_class<T> >::type> : mpl::true_
    {};*/
    
    
    BOOST_MPL_HAS_XXX_TEMPLATE_NAMED_DEF(is_metafunction_class, apply, false)
    
    template <typename T>
    struct is_apply_able : mpl::or_<is_metafunction_class<T>,mpl::is_lambda_expression<T> >
    {};
    
    struct plus_two
    {
        template <typename Number>
        struct apply
        {
            typedef typename mpl::plus<Number,mpl::int_<2> >::type type;
        };
    };
    
    template <typename T>
    struct Foo
    {};
    
    template <typename Partial, typename T>
    struct maybe_apply
    : mpl::eval_if<is_apply_able<Partial>,
        mpl::apply<Partial, T>,
        mpl::identity<Partial> > 
    { };
    
    int main()
    {
        std::cout << typeid(maybe_apply<Foo<mpl::_1>,int>::type).name() << std::endl;
        std::cout << typeid(maybe_apply<plus_two,mpl::int_<1> >::type).name() << std::endl;
        std::cout << typeid(maybe_apply<Foo<float>,int>::type).name() << std::endl;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-22
      • 2016-05-01
      • 1970-01-01
      • 2017-10-28
      • 1970-01-01
      • 2011-09-26
      • 2011-09-28
      • 1970-01-01
      相关资源
      最近更新 更多