On Sunday, 14 May 2017 at 20:18:24 UTC, Kevin Brogan wrote:
I have a piece of code that takes a callback function.
The callback has the signature void callback(void* state, void*
data)
There are several of these functions. All of them use state and
data as differing types.
As an example, let's look at one that uses both of them as int*.
addInt(void* state, void* data)
{
*cast(int*)state += *cast(int*)data;
}
Is it not possible to specify the cast as an alias so that I
can declare the cast once at the beginning of the function?
Something like this?
addInt(void* state, void* data)
{
alias _state = cast(int*)state; // Error: basic type
expected, not cast
alias _data = cast(int*)data; // Error: basic type
expected, not cast
*_state += *_data;
}
I can always do this:
addInt(void* state, void* data)
{
int* _state = cast(int*)state;
int* _data = cast(int*)data;
*_state += *_data;
}
But I don't want to create a new variable and assign it
everytime I call the function. The examples I'm using are
contrived, but in the c code I am porting this from, the
callback gets called thousands of times a second, every
optimization matters, and the variables are used many times per
function. I don't want to riddle the code with casts if i can
avoid it and I don't want to create and destroy useless proxy
variables every time the function is called.
1. Use template, that is what they are for
addInt(A, B)(A* state, B* data)
{
static if(is(B == int))
{
// B is an int if this block is called so no reason to
cast.
}
}
2. Use overloads, basically same as templates.
addInt(int* state, int* data)
{
}
3. Don't worry about it, any extra temp variables will almost
surely be optimized away.