2

I want to define a boost fusion::vector in my class with the size defined by a template parameter. ATM I'm doing this with a specialization of a helper class, but I think there should be a way to do this with boost mpl/fusion or something else in just one line.

namespace detail
{
    template<int dim, typename T>
    struct DimensionTupleSize
    { };
    template <typename T>
    struct DimensionTupleSize<1>
    {
        enum { Dimension = 1 }
        typedef boost::fusion::vector<T> type;
    };
    template <typename T>
    struct DimensionTupleSize<2>
    {
        enum { Dimension = 2 }
        typedef boost::fusion::vector<T, T> type;
    };
    template <typename T>
    struct DimensionTupleSize<3>
    {
        enum { Dimension = 3 }
        typedef boost::fusion::vector<T, T, T> type;
    };
}

template<int Dim = 2>
class QuadTreeLevel
{
public:
    detail::DimensionTupleSize<Dim>::type tpl;
};

Any ideas?

Vaughn Cato
  • 63,448
  • 5
  • 82
  • 132
Smittii
  • 187
  • 1
  • 10
  • 3
    Are you sure you should not be using a [`boost::array`](http://www.boost.org/doc/libs/release/doc/html/array.html) (`array` is also included in the C++11 standard library)? – Luc Touraille Feb 21 '12 at 19:55
  • Don't know why i didn't think about this. Might be the best solution. – Smittii Feb 21 '12 at 20:06

3 Answers3

4

You can do it recursively :

template<int N, class T> struct DimensionTupleSizeImpl
{
  typedef typename DimensionTupleSizeImpl<N-1,T>::type                   base;
  typedef typename boost::fusion::result_of::push_back<base,T>::type type;
};

template<class T> struct DimensionTupleSizeImpl<0,T>
{
  typedef boost::fusion::vector<> type;
};

template<int N, class T>
struct  DimensionTupleSize
      : boost::fusion::result_of::
        as_vector<typename DimensionTupleSizeImpl<N,T>::type>
{};
Joel Falcou
  • 6,247
  • 1
  • 17
  • 34
2

If you really want a tuple rather than an array, and you're simply looking for the most succinct solution..,

#include <boost/array.hpp>
#include <boost/fusion/include/boost_array.hpp>
#include <boost/fusion/include/as_vector.hpp>

template<std::size_t DimN, typename T>
struct DimensionTupleSize : boost::fusion::result_of::as_vector<
    boost::array<T, DimN>
>::type
{ };
ildjarn
  • 62,044
  • 9
  • 127
  • 211
1

You could use this:

template<int N, typename T>
struct create_tuple
{
private:
    template<int i, int n, typename ...U>
    struct creator;

    template<typename ...U>
    struct creator<N,N, U...>
    {
        typedef boost::fusion::vector<U...> type;
    };
    template<int i, typename ...U>
    struct creator<i, N,T, U...>
    {
        typedef typename creator<i+1,N,T,U...>::type type;
    };
public:
    typedef typename creator<1,N,T>::type type;
};

template<int N, class T>
struct  DimensionTupleSize
{
    typedef typename create_tuple<N,T>::type type;
};
Nawaz
  • 353,942
  • 115
  • 666
  • 851