opCast()

Let’s learn about the opCast function that is used for type conversions.

We'll cover the following

opCast for type conversions

opCast defines explicit type conversions. It can be overloaded separately for each target type. As you might remember from the earlier chapters, explicit type conversions are performed by the to function and the cast operator.

opCast is a template as well, but it has a different format; the target type is specified by the (T : target_type) syntax:

target_type opCast(T : target_type)() {
    // ...
}

This syntax will become clear later, after the templates chapter.

Let’s change the definition of Duration so that it has two members: hours and minutes. The operator that converts objects of this type to double can be defined as in the following code:

Get hands-on with 1400+ tech skills courses.