Universal Function Call Syntax (UFCS) in D Language

Written by on January 9, 2022 in D Language, Programming with 0 Comments

One of the many “cool’ features of Dlang is “Universal Funcion Call Syntax”, which permits non-member functions to be invoked using the member function call syntax. When you add to this the fact that this applies not just to user-defined types but to primitive types as well, things get interesting. 

Let us look at some examples to understand this feature. 

Here is our first example:

Example-1

Example 1

Here we have a user-defined type “A” with member function “foo()”. There is also a non-member function (“free” function) called “bar()” which takes “A” as its first argument. Line 28 shows how it is posible to call “bar()” as if it is a member function of “A”, in the same manner “foo()” is called. This is called UFCS in Dlang.

What about the other way? Can member functions be invoked using regular function call syntax? No, that is not possible. See below:

Example 2

Example 2

Line 26 is OK, but not Line 32. 

Another case to consider is having a non-member function with the same name as member function and with the first argument as the user-defined type. 

Take a look at this example:

Example 3

Example 3

Here, in addition to the member function “foo()” in A”, we also have a non-member function “foo()” taking “A” type as its only argument. In this case, how does UFCS work? Line 33 shows that the member function will be used even if the “signature” appears to be the same. This means UFCS comes into picture only when there is no member function with that name.

An additional rule is that functions declared in local scope (“nested” functions) are not considered for UFCS. This is shown in the following example:

Example 4

Example 4

Line 44 shows that the nested function cannot take advantage of UFCS feature.

Finally, it is worthwhile to point out that even primitive types in DLang can take advantage of UFCS. Here is how:

Example 5

Example 5

The above shows how a sequence of operations on an integer array can be elegantly expressed using “chaining”, thanks to UFCS!

Have a great weekend!

Tags: ,

Subscribe

If you enjoyed this article, subscribe now to receive more just like it.

Subscribe via RSS Feed

Leave a Reply

Your email address will not be published.

Top