Type switch in a @:generic function

87 views
Skip to first unread message

Haxiomic

unread,
Aug 3, 2015, 6:12:15 PM8/3/15
to Haxe
Is there a built-in way to switch type in a generic function?

For example, see this try.haxe: try.haxe.org/#01a43

@:generic
static function genericTest<T>(v:T){
    //how can we tell if we're in a genericTest_Int or genericTest_String?
}

...

genericTest("hi");
genericTest(42);

This generates genericTest_Int and genericTest_Float

Is there some way to switch on T at compile time, so the contents of the functions is different for each type?

I expect there's a macro solution, but I'm keen to learn if there's something that can be done in a few lines or so

Thanks,
George

Hugh

unread,
Aug 4, 2015, 1:21:51 AM8/4/15
to Haxe
   static function genericTest<T>(v:T){
       
//how can we tell if we're in a genericTest_Int or genericTest_String?

       
switch(Type.typeof(v))
       
{
         
case TInt: trace("IsInt " + v);
         
case TClass(String): trace("IsString " + v);
         
default:
       
}
   
}

You can use Type.typeof - this is a runtime thing (so you are limited to what you can write) - if you want a compile-time thing, I think you need a macro. 

Hugh

Haxiomic

unread,
Aug 5, 2015, 10:41:50 AM8/5/15
to Haxe
Thanks Hugh, I've had a look at a macro solution in the past but never managed to get access to T. Anyhow, if I figure out a compile-time switch I'll update this thread

Kevin ResoL

unread,
Aug 6, 2015, 12:51:20 AM8/6/15
to Haxe

Haxiomic

unread,
Aug 6, 2015, 10:59:41 AM8/6/15
to Haxe
Thanks for the heads up Kevin! (Saved me a bunch of time fiddling about with macros)

Looks like it's not going to be possible for a while, maybe haxe 4 ;)

Johann

unread,
Aug 22, 2015, 3:57:29 AM8/22/15
to Haxe


On Thursday, August 6, 2015 at 4:59:41 PM UTC+2, Haxiomic wrote:
Thanks for the heads up Kevin! (Saved me a bunch of time fiddling about with macros)

Looks like it's not going to be possible for a while, maybe haxe 4 ;)


A macro solution works if you call the macro at a point where type information is still available, so not inside a function that uses type parameters, but rather at the call site to that (to be replaced) function. IOW, you implement a `@:generic` function yourself. If you do that, you are also responsible for avoiding code duplication yourself - in the naive approach, you'd just generate the code for a certain set of types on every invocation all over again, which would completely unnecessarily blow up the code size, for any non-trivial function. 

regards,
Johann
 
Reply all
Reply to author
Forward
0 new messages