Choosing arity of a template function

Andrei Alexandrescu via Digitalmars-d digitalmars-d at puremagic.com
Fri Feb 26 15:11:32 PST 2016


On 02/26/2016 06:09 PM, Andrei Alexandrescu wrote:
> A generic function receives an argument called "partition" by alias.
> That may work in one of the following ways:
>
> partition(range);
>
> partition!less(range);
>
> partition!less(range, n); // n is a number
>
> I tried this:
>
> static if (is(partition == function) || is(partition == delegate))
>    partition(r);
> else if (__traits(compiles, partition!less(r, n)))
>    partition!less(r, n);
> else
>    partition!less(r);
>
> The first test works very nice. The second does not; the compiler
> attempts to instantiate the template wrongly and spits a bunch of errors
> before giving up, in spite of the whole "let me know silently whether
> this compiles" thing.
>
> So, what's an elegant solution to this? I looked up std.traits but
> nothing seems to help. (Tried arity, no avail.)

Urgh, forgot the "static" in front of the second "if". It does work now. 
Nevertheless, I'm still on lookout for a more elegant solution! I have 
this mindset that using __traits(compiles) is some sort of cheating.


Andrei



More information about the Digitalmars-d mailing list