Re:Better C – A subset of D Programming Language
by RandallBrown on Tuesday April 28, 2020 @01:25PM
(#23009386)
Interesting, so the return type isn't known until runtime.
[ Parent
| on HN ]
Re:Better C – A subset of D Programming Language
by gallier2 on Tuesday April 28, 2020 @02:45PM
(#23010361)
No. It is known at compile time.
Template declarations in D take 2 parameter lists. The first is the template parameters the second the runtime parameter: in auto whatDoesItReturn(int i)() { static if (i == 0) { return int.init; } else { return string.init; } }
we have (int i) as template parameter and () as an empty runtime parameter. In C++ syntax whatDoesItReturn<int i>()
at instanciation the syntax is different:
whatDoesItReturn!0() will instantiate a function returning an int
whatDoesItReturn!42() will instantiate a function returning a string.
Re:Better C – A subset of D Programming Language
by lumberjackstian on Tuesday April 28, 2020 @01:38PM
(#23009569)
When it comes to templates it's not until instantiation time - when the compiler see the code being used. So this is just an issue during compilation.
The docs on static if may shed some more light: https://dlang.org/spec/version.html#staticif
Re:Better C – A subset of D Programming Language
by RandallBrown on Tuesday April 28, 2020 @02:29PM
(#23010200)
So the previous code wouldn't compile unless the compiler knew what values were going to be passed into whatDoesItReturn?
Re:Better C – A subset of D Programming Language
by lumberjackstian on Tuesday April 28, 2020 @04:22PM
(#23011452)
Aye correct! I should've been more clear about that, sorry.
Template arguments need to be known at compile time, and the extra set of parens is how templates parameters are declared in D.
Re:Better C – A subset of D Programming Language
by DougBTX on Tuesday April 28, 2020 @03:46PM
(#23011013)
I missed this the first time, but there are two sets of parentheses in the example. Apparently the first set are like template parameters, and the second are the actual arguments to the function.