How can D solve this problem with return types?

C ++ 11 introduced a new syntax for declaring a function,

auto func(T rhs, U lhs) -> V 

This was supposed to solve some problems that arose in the old C ++ standard using function templates. Read this short section of the Wikipedia article to find out more about the problem:
> http://en.wikipedia.org/wiki/C% 2B% 2B11 # Alternative_function_syntax

My question is, is D handling the same problem? If so, how to fix it (if at all)?

+6
source share
2 answers

In D, the compiler can infer a return type for you. Therefore, there is no need to have syntax -> V

 auto func(T, U)(T lhs, U rhs) { return lhs + rhs; } 

or if you want to be more specific (but it's better to let the compiler figure out the type with auto !)

 typeof(T.init + U.init) func(T, U)(T lhs, U rhs) { return lhs + rhs; } 

Like C ++, you cannot use typeof(lhs + rhs) in this place.

+9
source

I'm not 100% sure, but I think you can use the typeof(<expression>) syntax. Therefore, it should be possible to do something like: typeof(rhs+lhs) func(T rhs, U lhs) { /* body */ }

0
source

Source: https://habr.com/ru/post/900923/


All Articles