4 ms·
What would be the return type of that? Does D have an Either type?
by RandallBrown 7y ago
What would be the return type of that? Does D have an Either type?
- lumberjackstian 7y agoDepends on the value of the template parameter. If it's 0 the return type is an int, if it's not 0 the return type is a string. There's a wanting implementation of a sumtype in the standard library (https://dlang.org/phobos/std_variant.html#.Algebraic https://dlang.org/phobos/std_variant.html#.Algebraic), and a much better one as a package: https://code.dlang.org/packages/sumtype https://code.dlang.org/packages/sumtype
- RandallBrown 7y agoInteresting, so the return type isn't known until runtime.
- lumberjackstian 7y agoWhen 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 https://dlang.org/spec/version.html#staticif
- RandallBrown 7y agoSo the previous code wouldn't compile unless the compiler knew what values were going to be passed into whatDoesItReturn?
- DougBTX 7y agoI 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.
- lumberjackstian 7y agoAye 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.
- gallier2 7y agoNo. 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.