Re: TMP type-picking
on Mon Oct 01 2007, "Jan C. Kleinsorge" <void-AT-none.arcor-online.net> wrote:
Hi everyone,
I am trying to get the program below to work. I'd like to define a type
that will automatically pick the first type in the typelist that is big
enough to hold the number of bytes given.
Like
AutoType<SignedIntList, 4>::Result i;
with
template <class T, class U>
struct TypeList {
typedef T Head;
typedef U Tail;
};
struct NullType {};
typedef TypeList<char,
TypeList<short,
TypeList<int,
TypeList<long,
TypeList<long long, NullType> > > > > SignedIntList;
template <class Tl, int i> struct AutoType;
template <class H, class T>
struct AutoType<TypeList<H, T>, 0> {
typedef H Result;
};
template<class H, class T, int i>
struct AutoType<TypeList<H, T>, i> {
typedef typename
AutoType<T, (sizeof(H) >= i) ? 0 : i>::Result Result;
};
Obviously, the final Result type-definition is just one step further
than the type needed. Like suggesting an (32bit here) int where a short
would've been enough.
Can you give me a hint on how I could trick this to work?
// untested
#include "boost/mpl/size_t.hpp"
#include "boost/mpl/find_if.hpp"
#include "boost/mpl/deref.hpp"
#include "boost/mpl/placeholders.hpp"
namespace mpl = boost::mpl;
using namespace mpl::placeholders;
template <class T>
struct sizeof_
: mpl::size_t<sizeof(T)>
{}
template <class TypeSequence, std::size_t N>
struct autotype
: mpl::deref<
typename mpl::find_if<
TypeSequence,
mpl::greater_equal<sizeof_<_1>, mpl::size_t<N> >
>::type
>
{};
#include "boost/mpl/vector.hpp"
typedef autotype<
mpl::vector<int, long, long long>, sizeof(short)
>::type short_holder;
My guess, however, is that you have overlooked alignment
considerations and you actually need
http://www.boost.org/doc/html/boost_typetraits/category.html#boost_typetraits.alignment
HTH,
--
Dave Abrahams
Boost Consulting
http://www.boost-consulting.com
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]