Search code examples
parameter-passingdefaultd

Skip a default parameter in D


I'm going through the D language tour and when I got to Functions started wondering if there's a way to skip a default parameter when calling a function, eg.:

import std.stdio;

void greet(string greeting = "Hello", string subject = "World")
{
    writefln("%s %s", greeting, subject);
}

void main()
{
    greet();
    greet("Howdy");
    greet("Hello", "D");  // duplicating default "Hello"
    // greet(, "D");      // Error: expression expected, not ','
}

I've already looked at How to enter by-name argument to a function in D?, so I know you can't pass parameters by name, and apart from that couldn't find any mention of such a feature, so asking just to make sure I didn't miss anything and there's a clear answer somewhere on the internet.

If it's not possible to skip passing a parameter when a default is available, what's the best practice for avoiding duplicating default values?


Solution

  • You cannot skip an argument, but if you know it has a default, you can automatically supply that default:

    import std.traits;
    

    ...

    greet(ParameterDefaults!greet[0], "D");