www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Template function type inference with default arguments

reply "ixid" <adamsibson hotmail.com> writes:
Why don't templates take a type from the default argument if 
nothing else is supplied? It would be useful to be able to use an 
enum to set a default.

enum MAX = 1_000;

auto sieve(T)(T max = MAX) {
	import std.bitmanip : BitArray;
	BitArray n;
	n.length = max;
	T[] primes = [2];

	for(T i = 3; i < max; i += 2)
		if(n[i] == 0) {
			primes ~= i;
			for(T j = i + i; j < max; j += i)
				n[j] = 1;
		}

	return primes;
}

Changing the type to T = typeof(MAX) works but feels 
unnecessarily clunky and out of step with how templates normally 
operate when supplied with an argument.
Jan 03 2015
next sibling parent "Meta" <jared771 gmail.com> writes:
On Sunday, 4 January 2015 at 00:22:01 UTC, ixid wrote:
 Why don't templates take a type from the default argument if 
 nothing else is supplied? It would be useful to be able to use 
 an enum to set a default.
I doubt anyone's ever thought of that particular use-case. Using your typeof(MAX) workaround is probably as good as it's going to get for the time being.
Jan 03 2015
prev sibling parent "anonymous" <anonymous example.com> writes:
On Sunday, 4 January 2015 at 00:22:01 UTC, ixid wrote:
 Why don't templates take a type from the default argument if 
 nothing else is supplied?
https://issues.dlang.org/show_bug.cgi?id=2803
Jan 05 2015