EP48 Variable Number of Parameters

201 阅读6分钟

This chapter covers two D features that bring flexibility on parameters when calling functions:

  • Default arguments
  • Variadic functions

48.1 Default arguments

A convenience with function parameters is the ability to specify default values for them. This is similar to the default initial values of struct members.

Some of the parameters of some functions are called mostly by the same values. To see an example of this, let's consider a function that prints the elements of an associative array of type string[string]. Let's assume that the function takes the separator characters as parameters as well:

import std.algorithm;

// ...

void printAA(string title, string[string] aa, string keySeparator, string elementSeparator) {
    writeln("-- ", title, " --");

    auto keys = sort(aa.keys);

    // Don't print element separator before the first element
    if (keys.length != 0) {
        auto key = keys[0];
        write(key, keySeparator, aa[key]);
        keys = keys[1..$];    // Remove the first element
    }

    // Print element separator before the remaining elements
    foreach (key; keys) {
        write(elementSeparator);
        write(key, keySeparator, aa[key]);
    }

    writeln();
}

That function is being called below with ":" as the key separator and ", " as the element separator:

void main() {
    string[string] dictionary = [
        "blue":"mavi",
        "red":"kırmızı",
        "gray":"gri"
    ];

    printAA("Color Dictionary", dictionary, ":", ", ");
}

The output:

-- Color Dictionary --
blue:mavi, gray:gri, red:kırmızı

If the separators are almost always going to be those two, they can be defined with default values:

void printAA(string title, string[string] aa, string keySeparator = ": ", string elementSeparator = ", ") {
    // ...
}

Parameters with default values need not be specified when the function is called:

printAA("Color Dictionary",
        dictionary);  /* ← No separator specified. Both
                       *   parameters will get their
                       *   default values. */

The parameter values can still be specified when needed, and not necessarily all of them:

printAA("Color Dictionary", dictionary, "=");

The output:

-- Color Dictionary --
blue=mavi, gray=gri, red=kırmızı

The following call specifies both of the parameters:

printAA("Color Dictionary", dictionary, "=", "\n");

The output:

-- Color Dictionary --
blue=mavi
gray=gri
red=kırmızı

Default values can only be defined for the parameters that are at the end of the parameter list.

Special keywords as default arguments

The following special keywords act like compile-time literals having values corresponding to where they appear in code:

类似编译时字面值。

  • __MODULE__: Name of the module as string
  • __FILE__: Name of the source file as string
  • __FILE_FULL_PATH__: Name of the source file including its full path as string
  • __LINE__: Line number as int
  • __FUNCTION__: Name of the function as string
  • __PRETTY_FUNCTION__: Full signature of the function as string

Although they can be useful anywhere in code, they work differently when used as default arguments. When they are used in regular code, their values refer to where they appear in code:

import std.stdio;

void func(int parameter) {
    writefln("Inside function %s at file %s, line %s.",
             __FUNCTION__, __FILE__, __LINE__);    // ← line 5
}

void main() {
    func(42);
}

The reported line 5 is inside the function:

Inside function deneme.func at file deneme.d, line 5.

However, sometimes it is more interesting to determine the line where a function is called from, not where the definition of the function is. When these special keywords are provided as default arguments, their values refer to where the function is called from:

import std.stdio;

void func(int parameter,
          string functionName = __FUNCTION__,
          string file = __FILE__,
          int line = __LINE__) {
    writefln("Called from function %s at file %s, line %s.",
             functionName, file, line);
}

void main() {
    func(42);    // ← line 12
}

This time the special keywords refer to main(), the caller of the function:

Called from function deneme.main at file deneme.d, line 12.

In addition to the above, there are also the following special tokens that take values depending on the compiler and the time of day:

下面取决于编译时的日期。

  • __DATE__: Date of compilation as string
  • __TIME__: Time of compilation as string
  • __TIMESTAMP__: Date and time of compilation as string
  • __VENDOR__: Compiler vendor as string (e.g. "Digital Mars D")
  • __VERSION__: Compiler version as long (e.g. the value 2081L for version 2.081)

48.2 Variadic functions

Despite appearances, default parameter values do not change the number of parameters that a function receives. For example, even though some parameters may be assigned their default values, printAA() always takes four parameters and uses them according to its implementation.

On the other hand, variadic functions can be called with unspecified number of arguments. We have already been taking advantage of this feature with functions like writeln(). writeln() can be called with any number of arguments:

writeln( "hello", 7, "world", 9.8 /*, and any number of other*  arguments as needed */);

There are four ways of defining variadic functions in D:

  • The feature that works only for functions that are marked as extern(C). This feature defines the hidden _argptr variable that is used for accessing the parameters. This book does not cover this feature partly because it is unsafe.
  • The feature that works with regular D functions, which also uses the hidden _argptr variable, as well as the _arguments variable, the latter being of type TypeInfo[]. This book does not cover this feature as well both because it relies on pointers, which have not been covered yet, and because this feature can be used in unsafe ways as well.
  • A safe feature with the limitation that the unspecified number of parameters must all be of the same type. This is the feature that is covered in this section.
  • Unspecified number of template parameters. This feature will be explained later in the templates chapters.

The parameters of variadic functions are passed to the function as a slice. Variadic functions are defined with a single parameter of a specific type of slice followed immediately by the ... characters:

不定参数的使用方法。

double sum(double[] numbers...) {
    double result = 0.0;

    foreach (number; numbers) {
        result += number;
    }

    return result;
}

That definition makes sum() a variadic function, meaning that it is able to receive any number of arguments as long as they are double or any other type that can implicitly be convertible to double:

writeln(sum(1.1, 2.2, 3.3));

The single slice parameter and the ... characters represent all of the arguments. For example, the slice would have five elements if the function were called with five double values.

In fact, the variable number of parameters can also be passed as a single slice:

writeln(sum([ 1.1, 2.2, 3.3 ]));    // same as above

Variadic functions can also have required parameters, which must be defined first in the parameter list. For example, the following function prints an unspecified number of parameters within parentheses. Although the function leaves the number of the elements flexible, it requires that the parentheses are always specified:

char[] parenthesize(
    string opening,  // ← The first two parameters must be
    string closing,  //   specified when the function is called
    string[] words...) {  // ← Need not be specified
    char[] result;

    foreach (word; words) {
        result ~= opening;
        result ~= word;
        result ~= closing;
    }

    return result;
}

The first two parameters are mandatory:

parenthesize("{");     // ← compilation ERROR

As long as the mandatory parameters are specified, the rest are optional:

writeln(parenthesize("{", "}", "apple", "pear", "banana"));

The output:

{apple}{pear}{banana}

Variadic function arguments have a short lifetime

The slice argument that is automatically generated for a variadic parameter points at a temporary array that has a short lifetime. This fact does not matter if the function uses the arguments only during its execution. However, it would be a bug if the function kept a slice to those elements for later use:

使用切片参数提供的不定参数有着短生命周期。

int[] numbersForLaterUse;

void foo(int[] numbers...) {
    numbersForLaterUse = numbers;    // ← BUG
}

struct S {
    string[] namesForLaterUse;

    void foo(string[] names...) {
        namesForLaterUse = names;    // ← BUG
    }
}

void bar() {
    foo(1, 10, 100);  // The temporary array [ 1, 10, 100 ] is not valid beyond this point.

    auto s = S();
    s.foo("hello", "world");  // The temporary array [ "hello", "world" ] is not valid beyond this point.

    // ...
}

void main() {
    bar();
}

Both the free-standing function foo() and the member function S.foo() are in error because they store slices to automatically-generated temporary arrays that live on the program stack. Those arrays are valid only during the execution of the variadic functions.

独立函数foo()和成员函数S.foo()都是错误的,因为它们将片存储到程序堆栈上自动生成的临时数组中。这些数组仅在执行可变参数函数期间有效。

For that reason, if a function needs to store a slice to the elements of a variadic parameter, it must first take a copy of those elements:

因此,如果一个函数需要存储可变参数元素的切片,必须首先获取这些元素的副本。

void foo(int[] numbers...) {
    numbersForLaterUse = numbers.dup;    // ← correct
}

// ...

    void foo(string[] names...) {
        namesForLaterUse = names.dup;    // ← correct
    }

However, since variadic functions can also be called with slices of proper arrays, copying the elements would be unnecessary in those cases.

由于可变参数函数也可以用适当的数组切片来调用,因此在这种情况下复制元素是不必要的。

A solution that is both correct and efficient is to define two functions having the same name, one taking a variadic parameter and the other taking a proper slice. If the caller passes variable number of arguments, then the variadic version of the function is called; and if the caller passes a proper slice, then the version that takes a proper slice is called:

一个既正确又有效的解决方案是定义两个具有相同名称的函数,一个接受可变参数,另一个接受适当的切片。如果调用者传递可变数量的参数,则调用函数的可变类型版本;如果调用者传递了一个正确的切片,那么接受一个正确切片的版本将被调用。

int[] numbersForLaterUse;

void foo(int[] numbers...) {
    /* Since this is the variadic version of foo(), we must
     * first take a copy of the elements before storing a
     * slice to them. */
    numbersForLaterUse = numbers.dup;
}

void foo(int[] numbers) {
    /* Since this is the non-variadic version of foo(), we can
     * store the slice as is. */
    numbersForLaterUse = numbers;
}

struct S {
    string[] namesForLaterUse;

    void foo(string[] names...) {
        /* Since this is the variadic version of S.foo(), we
         * must first take a copy of the elements before
         * storing a slice to them. */
        namesForLaterUse = names.dup;
    }

    void foo(string[] names) {
        /* Since this is the non-variadic version of S.foo(),
         * we can store the slice as is. */
        namesForLaterUse = names;
    }
}

void bar() {
    // This call is dispatched to the variadic function.
    foo(1, 10, 100);

    // This call is dispatched to the proper slice function.
    foo([ 2, 20, 200 ]);

    auto s = S();

    // This call is dispatched to the variadic function.
    s.foo("hello", "world");

    // This call is dispatched to the proper slice function.
    s.foo([ "hi", "moon" ]);

    // ...
}

void main() {
    bar();
}

Defining multiple functions with the same name but with different parameters is called function overloading, which is the subject of the next chapter.