static if else behavior and is type comparison

Fynn Schröder via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Mar 11 00:02:41 PST 2016


Hi all,

I'm currently working on a small utility to control the EC 
(embedded controller) of my notebook. I need to call an external 
C library and choose different methods based on the desired 
return type. I came up with a solution based on type checking and 
static if - however I ran into a weird issue:

void main()
{
	pragma(msg, "only ubytes:");
	ubyte x = typeBasedDispatcher!ubyte();
	
	pragma(msg, "only ushorts:");
	ushort y = typeBasedDispatcher!ushort();
	
	pragma(msg, "only uints:");
	uint z = typeBasedDispatcher!uint();
}

U typeBasedDispatcher(U)() if (is(U == ubyte) || is(U == ushort) 
|| is(U == uint)) {
	static if (is(U == ubyte)) {
		pragma(msg, "is ubyte");
		return fnUbyte();
	} else if (is(U == ushort)) {
		pragma(msg, "is ushort");
		return fnUshort();
	} else if (is(U == uint)) {
		pragma(msg, "is unit");
		return fnUint();
	} else {
		pragma(msg, "ERROR!? should not reach this in any case!?");
	}
}

ubyte fnUbyte() { return ubyte.init; }

ushort fnUshort() { return ushort.init; }

uint fnUint() { return uint.init; }

Output of dmd 2.070.0 on Windows:

only ubytes:
is ubyte
only ushorts:
is ushort
is unit
ERROR! should not reach this in any case!
staticIfElse.d(22): Error: cannot implicitly convert expression 
(fnUint()) of type uint to ushort
staticIfElse.d(7): Error: template instance 
staticIfElse.typeBasedDispatcher!ushort error instantiating
only uints:
is ushort
is unit
ERROR! should not reach this in any case!


Am I doing anything wrong here or is this a bug?



More information about the Digitalmars-d-learn mailing list