On Fri, 17 Apr 2009 06:11:00 +0400, Doctor J <[email protected]> wrote:
OK, here's one for you that sounds like it ought to be easy, but I don't
immediately see how to do it in a pretty way.
Given a type parameter T of a template:
If T is an integral type, I want to declare a variable 'widest' of type
ulong;
If T is a floating-point type, I want to declare a variable 'widest' of
type double.
And it has to be prettier than my solution. :)
static if (is (T: ulong))
ulong widest = 0;
else if (is (T: double))
double widest = 0.0;
else
static assert (false, "Unimplemented type " ~ T.stringof) ;
Now, I thought this sounds like a great job for a mixin:
template Widen (T, alias varname)
{
static if (is (T: ulong))
ulong varname = 0;
else if (is (T: double))
double varname = 0.0;
else
static assert (false, "Unimplemented type " ~ T.stringof) ;
}
mixin Widen!(T, widest);
...but alas, "Declaration expected, not 'if'".
Help?
I would avoid mixin in such situation and use template instead:
template Widen(T)
{
static if (is(T : ulong)) {
alias ulong Widen;
} else static if (is(T : double)) {
alias double Widen;
} else {
static assert (false, "Unimplemented type " ~ T.stringof) ;
}
}
Widen!(T) widest;