type determination

Ali Çehreli acehreli at yahoo.com
Mon Nov 26 21:11:11 PST 2012


On 11/26/2012 09:03 PM, dsmith wrote:
> How can I make something like the following work without "Error: cannot
> append type double to type string[]" ?
>
>
> T[] some_function(T[] var) {
> T[] var2;
> double a = 12.34;
> string b = "hello";
>
> if(typeof(var).stringof == "double") {
> var2 ~= a;
> }
> if(typeof(var).stringof == "string") {
> var2 ~= b;
> }
>
> ...
> }
>
>

One way is to dispatch the selection to a "traits" template:

template valueToAdd(T : double)
{
     T valueToAdd = 12.34;
}

template valueToAdd(T : string)
{
     T valueToAdd = "hello";
}


T[] some_function(T)(T[] var) {
     T[] var2;
     var2 ~= valueToAdd!T;
     return var2;
}

import std.stdio;

void main()
{
     writeln(some_function([ 1.25, 2.75 ]));
     writeln(some_function([ "abc", "xyz" ]));
}

Ali


More information about the Digitalmars-d-learn mailing list