Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

d
dlang

What are overload sets in D?

Hamza Mehmood

Overview

In D language, the overload sets are functions that are declared and overloaded in the same scope.

Let's look at some simple examples to understand how overloading sets work in the D language.

Code example 1

In the example below, we have two functions defined in the same module.

module One;
void fun(){ }
void fun(long i) { } 
Overloaded functions defined in the module level

So, both functions, One.fun() and One.fun(long), collectively form an overload set.

Now, let's look at a slightly more complex example.

Code example 2

Let's assume we have a second module called Two that contains an overload set of functions with the same name as the module One.

module Two;
class C { }
void fun(C) { }
void fun(int i) { }
Declaration of module Two

What would happen if we want to import these modules into a third module and attempt to call the functions from the overload sets? Let's find out through an example:

import One;
import Two;

void bar(C c , long i)
{
    fun();      // calls One.fun()
    fun(i);     // calls One.fun(long)
    fun(c);     // calls Two.fun(C)
    fun(1,2);   // error, does not match any fun
    fun(1);     // error, matches One.fun(long) and Two.fun(int)
    One.fun(1); // calls One.fun(long)
}
Importing the two modules in a third one

Each function call compares the arguments with the defined functions and selects the one with the best matching arguments. However, an unexpected error is present in line 10. This is because the arguments for the call match two functions in separate overload sets. As a result, the compiler does not know which module it is supposed to call the function from.

To remedy this, we can merge our two modules using an alias declaration. Let's look at the code snippet below:

main.d
Two.d
One.d
import One;
import Two;

alias fun = One.fun;
alias fun = Two.fun;

void bar(C c , long i)
{
    fun();      // calls One.fun()
    fun(i);     // calls One.fun(long)
    fun(c);     // calls Two.fun(C)
    //fun(1,2);   // error, does not match any fun
    fun(2);     // calls Two.fun(int)
    One.fun(1); // calls One.fun(long)
}

void main(){
    auto c = new C;
    long i = 0;
    bar(c, i);
}
Adding an alias to merge the two overload sets

In line 13, we see that the error we previously got is gone because we merge the two sets into an alias from which the function arguments can be matched.

RELATED TAGS

d
dlang
RELATED COURSES

View all Courses

Keep Exploring