Map one tuple to another Tuple of different type
Daniel Gibson via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sun Jul 20 15:55:34 PDT 2014
Hi,
I have a variadic templated function and want to call a C varargs
function. I want to be able to pass static arrays, which D2 passes by
value and C by reference, so I'd like to automagically translate those
arguments.
My idea was something like this:
extern (C) origFun(int x, ...);
T transTupleElem(T)(T arg) { return arg; }
float* transTupleElem(T : float[3])(T arg) {
return arg.ptr;
}
void fun(T...)(int x, T argTuple) {
// create a new tuple type that replaces all static float[3]
// arrays with float* to emulate C call-by-reference behavior
alias ReplaceAll!(float[3], float*, T) ModifiedTuple;
ModifiedTuple modTuple;
foreach(size_t i ; 0 .. T.length)
modTuple[i] = transTupleElem(argTuple[i]); // BOOM!
origFun(modTuple); // or is it modTuple.expand ?
}
However, this doesn't work (dmd 2.065 linux64), because:
"Error: variable i cannot be read at compile time"
In C++11 (where almost everything else about variadic templates is
pretty painful), this could probably be done like:
template<typename... T>
void fun(T... args)
{
origFun( transTupleElem(args)... );
}
so I guess it shouldn't be too hard to do something equivalent in D?
I looked for some kind of staticMap() function that could map values
from one tuple to another (of the same type), but only found
std.typetuple.staticMap() which only seems to modify types in
TypeTuples, not values in tuple instances.
Cheers,
Daniel
More information about the Digitalmars-d-learn
mailing list