Programming in D – Tutorial and Reference
Ali Çehreli

Other D Resources

Function Overloading

Defining more than one function having the same name is function overloading. In order to be able to differentiate these functions, their parameters must be different.

The following code has multiple overloads of the info() function, each taking a different type of parameter:

import std.stdio;

void info(double number) {
    writeln("Floating point: ", number);
}

void info(int number) {
    writeln("Integer       : ", number);
}

void info(string str) {
    writeln("String        : ", str);
}

void main() {
    info(1.2);
    info(3);
    info("hello");
}

Although all of the functions are named info(), the compiler picks the one that matches the argument that is used when making the call. For example, because the literal 1.2 is of type double, the info() function that takes a double gets called for it.

The choice of which function to call is made at compile time, which may not always be easy or clear. For example, because int can implicitly be converted to both double and real, the compiler cannot decide which of the functions to call in the following program:

real sevenTimes(real value) {
    return 7 * value;
}

double sevenTimes(double value) {
    return 7 * value;
}

void main() {
    int value = 5;
    auto result = sevenTimes(value);    // ← compilation ERROR
}

Note: It is usually unnecessary to write separate functions when the function bodies are exactly the same. We will see later in the Templates chapter how a single definition can be used for multiple types.

However, if there is another function overload that takes a long parameter, then the ambiguity would be resolved because long is a better match for int than double or real:

long sevenTimes(long value) {
    return 7 * value;
}

// ...

    auto result = sevenTimes(value);    // now compiles
Overload resolution

The compiler picks the overload that is the best match for the arguments. This is called overload resolution.

Although overload resolution is simple and intuitive in most cases, it is sometimes complicated. The following are the rules of overload resolution. They are being presented in a simplified way in this book.

There are four states of match, listed from the worst to the best:

The compiler considers all of the overloads of a function during overload resolution. It first determines the match state of every parameter for every overload. For each overload, the least match state among the parameters is taken to be the match state of that overload.

After all of the match states of the overloads are determined, then the overload with the best match is selected. If there are more than one overload that has the best match, then more complicated resolution rules are applied. I will not get into more details of these rules in this book. If your program is in a situation where it depends on complicated overload resolution rules, it may be an indication that it is time to change the design of the program. Another option is to take advantage of other features of D, like templates. An even simpler but not always desirable approach would be to abandon function overloading altogether by naming functions differently for each type e.g. like sevenTimes_real() and sevenTimes_double().

Function overloading for user-defined types

Function overloading is useful with structs and classes as well. Additionally, overload resolution ambiguities are much less frequent with user-defined types. Let's overload the info() function above for some of the types that we have defined in the Structs chapter:

struct TimeOfDay {
    int hour;
    int minute;
}

void info(TimeOfDay time) {
    writef("%02s:%02s", time.hour, time.minute);
}

That overload enables TimeOfDay objects to be used with info(). As a result, variables of user-defined types can be printed in exactly the same way as fundamental types:

    auto breakfastTime = TimeOfDay(7, 0);
    info(breakfastTime);

The TimeOfDay objects would be matched with that overload of info():

07:00

The following is an overload of info() for the Meeting type:

struct Meeting {
    string    topic;
    size_t    attendanceCount;
    TimeOfDay start;
    TimeOfDay end;
}

void info(Meeting meeting) {
    info(meeting.start);
    write('-');
    info(meeting.end);

    writef(" \"%s\" meeting with %s attendees",
           meeting.topic,
           meeting.attendanceCount);
}

Note that this overload makes use of the already-defined overload for TimeOfDay. Meeting objects can now be printed in exactly the same way as fundamental types as well:

    auto bikeRideMeeting = Meeting("Bike Ride", 3,
                                   TimeOfDay(9, 0),
                                   TimeOfDay(9, 10));
    info(bikeRideMeeting);

The output:

09:00-09:10 "Bike Ride" meeting with 3 attendees
Limitations

Although the info() function overloads above are a great convenience, this method has some limitations:

Exercise

Overload the info() function for the following structs as well:

struct Meal {
    TimeOfDay time;
    string    address;
}

struct DailyPlan {
    Meeting amMeeting;
    Meal    lunch;
    Meeting pmMeeting;
}

Since Meal has only the start time, add an hour and a half to determine its end time. You can use the addDuration() function that we have defined earlier in the structs chapter:

TimeOfDay addDuration(TimeOfDay start,
                      TimeOfDay duration) {
    TimeOfDay result;

    result.minute = start.minute + duration.minute;
    result.hour = start.hour + duration.hour;
    result.hour += result.minute / 60;

    result.minute %= 60;
    result.hour %= 24;

    return result;
}

Once the end times of Meal objects are calculated by addDuration(), DailyPlan objects should be printed as in the following output:

10:30-11:45 "Bike Ride" meeting with 4 attendees
12:30-14:00 Meal, Address: İstanbul
15:30-17:30 "Budget" meeting with 8 attendees