On Sunday, 10 January 2016 at 10:10:46 UTC, zabruk70 wrote:
Hello.

1st Novice question:

i want function, operates sometimes with char[], sometimes with ubyte[].
internally it works with ubyte.
i can use overloading:

void myFunc(ubyte[] arg) {...};
void myFunc(char[] arg) { ubyte[] arg2 = cast(ubyte[]) arg; ...}

It is OK. But i want 2 params (arg1, arg2),
so i need write 4 overloading functions.

I fill templated needed, can anybody show me the way?

No you actually don't have to write all possible overloads.

For example:
(surely not the best solution)

import std.traits;

ubyte[] myFuncImpl(ubyte[] a, ubyte[] b)
{
        return a ~ b;
}

ubyte[] myFunc(T1,T2)(T1[] a, T2[] b)
        if(is(Unqual!T1 == ubyte) || is(Unqual!T1 == char)
                || is(Unqual!T2 == ubyte) || is(Unqual!T2 == char))
{
        return myFuncImpl(cast(ubyte[]) a, cast(ubyte[]) b);
}


And 2nd question:

what if additionally to written above, function shuld return ubyte[] or char[] ?
can compiler guess what return type need from code?

No. Your function call signature would be completely the same..

The way to do this is to make the function a template and pass the return parameter to it.
So you're able to do something like:

auto val = myReturnFunc!int();


togrue


Reply via email to