Return enum-templated struct based on runtime value
Sebastian Graf
SebastianGraf at t-online.de
Fri Apr 5 07:26:24 PDT 2013
Hi,
I wonder if there is a good way to dry up this:
enum Machine
{
I386,
AMD64
// , ...
}
template machineWord(Machine machine)
{
static if (machine == Machine.I386)
{
alias machineWord = uint;
}
static if (machine == Machine.AMD64)
{
alias machineWord = ulong;
}
}
ulong foo(Machine machine)
{
if (machine == Machine.I386)
{
machineWord!(Machine.I386) m = (1 << 32)-1;
m++;
return m;
}
else // assume AMD64
{
machineWord!(Machine.AMD64) m = (1 << 32)-1;
m++;
return m;
}
}
Essentially, I am doing the same with each machine type, but it
has different semantics for each of them. I hope you see this is
a valid use case and a way to remove duplication.
Something à la specify the enum members to switch on to a
template together with a templated function and then do some
compile time magic to expand the code to invoke the appropriate
specialization.
More information about the Digitalmars-d-learn
mailing list