Choosing arity of a template function

Dicebot via Digitalmars-d digitalmars-d at puremagic.com
Mon Feb 29 03:37:47 PST 2016


On 02/27/2016 01:09 AM, Andrei Alexandrescu wrote:
> 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.)

Untested:

bool hasArityOverload ( alias F ) ( )
{
    import std.traits;
    if (!isSomeFunction!(F!less))
        return false;
    alias ParamTypes = Parameters!(F!less);
    if (ParamTypes.length != 2)
        return false;
    return isInputRange!(ParamTypes[0]) && is(ParamTypes[0] : uint);
}

Much more verbose but kess chance of accidental passing/failing by
unrelated reasons. In "casual" application code I'd still probably go
with `__traits(compiles)`.


More information about the Digitalmars-d mailing list