2

I am learning Boost.MPL and I am just starting. So please forgive me if solution is obvios. I look at such sample:

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

and cant help but wonder how to get rid of boost::mpl::vector when calling FooALL (turn it into a.FooAll<int, float, long>();) and for each argument call some static/global/or class internal function, not *this that confuses me?

4

1 回答 1

2

请查看 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 标准功能。但请确保您所针对的编译器已经支持此功能。

最好的问候, 马辛

于 2011-11-30T23:24:11.560 回答