【问题标题】:C++ Boost MPL: how to get rid of vector and callnot internal function?C++ Boost MPL:如何摆脱vector和callnot内部函数?
【发布时间】:2011-11-30 07:44:42
【问题描述】:

我正在学习 Boost.MPL,我才刚刚开始。因此,如果解决方案是明显的,请原谅我。我看这样的样本:

#include <boost/mpl/vector.hpp>
#include <boost/mpl/for_each.hpp>
#include <iostream>

using namespace std;

struct A
{
    template <class T>
    void    operator()(T t)
    {
        cout << typeid(T).name() << "\t" << t << endl;
    }

    template <class TypeVector>
    void    FooAll(void)
    {
        boost::mpl::for_each<TypeVector>(*this);
    }
};

void main(void)
{
    A   a;
    a.FooAll<boost::mpl::vector<int, float, long>>();
}

并且不禁想知道如何在调用 FooALL 时摆脱boost::mpl::vector(将其转换为a.FooAll&lt;int, float, long&gt;();)并且为每个参数调用一些静态/全局/或类内部函数,而不是让我感到困惑的*this

【问题讨论】:

    标签: c++ boost boost-mpl


    【解决方案1】:

    请查看 boost tuple 的实现(解决了类似的问题)。主要思想是您可以为 FollAll<...>() 方法指定最大数量的模板参数,并为其中的大多数提供默认类型。这是我的想法的草图

    #include <boost/type_traits/is_same.hpp>
    #include <boost/mpl/eval_if.hpp>
    #include <boost/mpl/vector.hpp>
    #include <boost/mpl/push_back.hpp>
    
    using boost::is_same;
    using boost::mpl::eval_if;
    using boost::mpl::vector;
    using boost::mpl::push_back;
    
    struct EmptyType {  };
    
    struct A
    {
      template<typename arg1, typename arg2=EmptyType, typename arg3=EmptyType, ..., typename argN=EmptyType>
      void    FooAll() {
          // reconstruct the type vector for easy manipulation later
          // Bolierplate code!
          typedef vector<arg>   vector_arg1;       
          typedef typename eval_if<is_same<arg2, EmptyType>,
                                    vector_arg1,
                                    push_back<vector_arg1, arg2> >::type  vector_arg2;
          typedef typename eval_if<is_same<arg3, EmptyType>,
                                    vector_arg2,
                                    push_back<vector_arg2, arg3> >::type  vector_arg3;
          //... rest of arguments
          typedef typename eval_if<is_same<argN, EmptyType>,
                                    vector_arg(N-1),
                                    push_back<vector_arg(N-1), argN> >::type  vector_argN;
    
          // now you can manipulate the reconstructed type vector
          Do_some_internal_stuff<vector_argN>::apply();
      }
    }
    

    如果您想要“高科技”,您可以尝试名为Variadic Templates 的 C++11 标准功能。但请确保您所针对的编译器已经支持此功能。

    最好的问候, 马辛

    【讨论】:

    • @user1072853 我已经用更多细节更新了这个例子。我无权访问编译器,因此请将此代码仅视为草图。
    猜你喜欢
    • 2011-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-25
    • 1970-01-01
    • 2020-09-18
    • 1970-01-01
    相关资源
    最近更新 更多