Function Overloading - D Programming Language

Menu

- Learn
- Documentation
  - Language Reference
  - Library Reference
  - Command-line Reference
  - Feature Overview
  - Articles
- Downloads
- Packages
- Community
  - Blog
  - Orgs using D
  - Twitter
  - Calendar
  - Discord (community-run)
  - Forums
  - IRC
  - Wiki
  - Issues
  - Contributing
  - Contributors
  - Foundation
  - Security Team
  - Donate
  - Sponsors
- Resources
  - Tour
  - Books
  - Tutorials
  - Tools
  - Editors
  - IDEs
  - run.dlang.io
  - Visual D
  - Acknowledgments
  - D Style
  - Glossary
  - Sitemap

Search
Report a bug
If you spot a problem with this page, click here to create a Bugzilla issue.
Improve this page
Quickly fork, edit online, and submit a pull request for this page. Requires a signed-in GitHub account. This works well for small changes. If you'd like to make larger changes you may want to consider using a local clone.

# 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);    // ← derleme HATASI
    }

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:

- mismatch
- match through automatic type conversion
- match through `const` qualification
- exact match

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:

- `info()` always prints to `stdout`. It would be more useful if it could print to any `File`. One way of achieving this is to pass the output stream as a parameter as well e.g. for the `TimeOfDay` type:

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

  That would enable printing `TimeOfDay` objects to any file, including `stdout`:

          info(stdout, breakfastTime);

          auto file = File("a_file", "w");
          info(file, breakfastTime);

  Note: The special objects `stdin`, `stdout`, and `stderr` are of type `File`.

- More importantly, `info()` does not solve the more general problem of producing the string representation of variables. For example, it does not help with passing objects of user-defined types to `writeln()`:

          writeln(breakfastTime);  // Not useful: prints in generic format

  The code above prints the object in a generic format that includes the name of the type and the values of its members, not in a way that would be useful in the program:

      TimeOfDay(7, 0)

  It would be much more useful if there were a function that converted `TimeOfDay` objects to `string` in their special format as in `"12:34"`. We will see how to define `string` representations of struct objects in the next chapter.

##### Problem

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

... çözüm

Copyright © 1999-2026 by the D Language Foundation | Page generated by Ddoc on Mon Aug 17 18:57:11 2026