Question

I am new to boost::mpl and TMP. I am trying to build a class as follows -

template< typename T > 
class Demo
{
public:
    typedef boost::mpl::size<T> NumDimensions;

    template< size_t D >
    struct Dim
    {
        typedef typename boost::mpl::at_c< T, D >::type Type;
    };

    //I want to implement this function
    template< size_t D >
    typename Dim<D>::Type GetElement() 
    {
        if(D == 0)
        {
            return element1_;
        }
        if(D == 1)
        {
            return element2_;
        }
        ....
    }

private:
    typename Dim<0>::Type element1_;
    typename Dim<1>::Type element2_;
    ....
};

And I plan to use this class as follows -

typedef Demo< boost::mpl::vector< int, float, long > > D1;
D1 d;
D1::Dim<0>::Type i = d.GetElement<0>();

I am curious to know if there is any better way to declare these elements rather than hard-coding and repeating their declarations (and returns) - something (may be) like an array with heterogeneous types and simpler access to the elements.

Note:- This code may have compiler errors (I didn't test it), but I hope it conveys my question.

Was it helpful?

Solution

You should find a way to create a tuple from your typelist. Here is an article that seems to describe how this could be done with C++11 featuers. http://www.devx.com/cplus/Article/41533/1954 There was also a talk by Stephen Lavavej on "Going Native 2012".

OTHER TIPS

I ended up using boost::fusion::vector as follows -

#include <iostream>
#include <tuple>
#include <string>

#include <boost/mpl/vector.hpp>
#include <boost/mpl/size.hpp>
#include <boost/mpl/at.hpp>

#include <boost/fusion/include/mpl.hpp>
#include <boost/fusion/container.hpp>


using namespace boost;
using namespace std;

template< typename T > 
class Demo
{
public:
    typedef boost::mpl::size<T> NumDimensions;

    template< size_t D >
    struct Dim
    {
        typedef typename boost::mpl::at_c< T, D >::type Type;
    };

    template< size_t D >
    typename Dim<D>::Type& GetElement()
    {
        return fusion::at_c<D>(elements_);
    }

private:
    typename fusion::result_of::as_vector< T >::type elements_;
};
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top