Help needed to learn typeof(return)

Steven Schveighoffer schveiguy at gmail.com
Sun Mar 27 01:11:02 UTC 2022


On 3/26/22 2:25 PM, Vinod K Chandran wrote:
> Hi all,
> I am reading `Programming in D` online book. There is a paragraph in the 
> chapter `More Templates`.
> ```
> typeof(return) generates the return type of a function, inside that 
> function.
> For example, instead of defining the calculate() function above as an 
> auto function, we can be more explicit by replacing auto with 
> LargerOf!(A, B) in its definition. (Being more explicit would have the 
> added benefit of obviating at least some part of its function comment.)
> ```
> And it shows this code.
> ```d
> LargerOf!(A, B) calculate(A, B)(A a, B b) {
>      typeof(return) result;    // The type is either A or B
>      // ...
>      return result;
> }
> ```
> The author says `LargerOf!(A, B)` is used instead of `auto` keyword. How 
> did compiler understands the return type from `LargerOf!(A, B)`.
> 

Not sure what the question here is, typeof(return) is the type that is 
returned from the function.

Where it is useful is if you don't really know what the return type is 
(i.e. an auto function) and you need to declare a variable of that type.

In this case, typeof(return) is really `Larger!(A, B)` which is likely 
aliased to either A or B.

The equivalent here is:

`LargerOf!(A, B) result;`

But the *spirit* of it is, "I don't want to have to think about whether 
it's A or B, just whatever it is, declare a variable of it here".

Hope that helps.

And yes, you can get into paradoxical problems like:

```d
auto foo()
{
    typeof(return) x;
    return x;
}
```

which will not compile.

-Steve


More information about the Digitalmars-d-learn mailing list