Re: TMP type-picking
Jan C. Kleinsorge 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?
Add a Select template to select a type
template <class First, class Second, bool B>
struct Select
{
typedef Second Type;
};
template <class First, class Second>
struct Select<First, Second, true>
{
typedef First Type;
};
and change your partial specialization of AutoType to
template<class H, class T, int i>
struct AutoType<TypeList<H, T>, i> {
typedef typename
Select
<
H,
typename AutoType<T, (sizeof(H) >= i) ? 0 : i>::Result,
(sizeof(H) >= i)
>::Type Result;
};
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]