Overloading Based on Constraints

jmh530 via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Jul 23 14:58:29 PDT 2015


I was looking at
http://dlang.org/concepts.html
where it discusses overloading templates based on constraints. I 
wanted to try to overload a template function with another 
version that does everything in place. So basically, one has a 
return and the other doesn't. However, when I run the code, it 
only calls the first function. The second one is ignored. I tried 
a number of adjustments, but the only thing that worked is to 
re-name the function something else, remove the U's, and just 
have it be a void function.


import std.stdio : writeln;
import std.traits;

T test(T)(T x)
	if (isNumeric!(T))
{
	writeln("calling test without void");
	T y = x;
	y += 1;
	return y;
}

U test(T, U)(ref T x)
	if (isNumeric!(T) && is(U == void))
{
	writeln("calling test with void");
	x += 2;
}

void main()
{
	int a = 1;
	int b = test(a);
	writeln(b);
	int c = b;
	test(c);
	writeln(c);
}


More information about the Digitalmars-d-learn mailing list