How is this code supposed to work?
AndreasDavour
andreas.davour at protonmail.ch
Fri Jan 25 20:14:53 UTC 2019
On Friday, 25 January 2019 at 14:25:33 UTC, AndreasDavour wrote:
>> https://run.dlang.io/is/a4oDFZ is an example of how this
>> looks. I feel like there's more to these templates than meet
>> the eye.
>
> To clarify. I really don't understand the thinking behind these
> templates, and wonder a bit about why a tutorial text like that
> contains examples that doesn't compile. There must be a
> conceptual unclarity somewhere I feel, not just where the
> parenthesis goes.
Finally the penny dropped. So for the poor sods who will find
this in a web search in the future, I will add to my my monologue
and show off both my stupidity and maybe some hints on how to
understand what was going on. I know nothing of C++ and if
templates are a concept from there, so maybe that was why I did
not get it.
The chapter from "Programming D" I was referring to in my first
post did start to talk about function templates, and then moved
on to step by step show templating of structs, and functions to
work upon those. What I did not grasp was that these were all
part of the code. The author made me think, by his choice of
words or my preconceptions I do not know, that he showed
incremental additions to the function template and sequentially
the struct template, when he was in fact showing new templates
all together. So, if I included all the templates, specializing
on Point, and then string, and only T, and so on, it worked as
intended.
What I did not grasp with the code of this template:
Point!T getResponse(T : Point!T)(string question) {
writefln("%s (Point!%s): ", question, T.stringof);
auto x = getResponse!T(" x");
auto y = getResponse!T(" y");
return Point!T(x, y);
}
was that the "inner" call to getResponse() is not a private
method within this scope, and thus dispatching on the same type
(which would make it recursive), but if you had that other
templates specializing on other types it would call the correct
function. I had the templating system down as a one pass
search-and-replace, but it's clearly more dynamic than that. So I
was correct there was a conceptual un-clarity present. With me.
This brings up an interesting point. How do you write a text that
teaches these things? If you break up the code in small blocks
where you explain the concepts step by step, and show variants
and how you can expand the abilities of the code by using more
and more complex features, how do you do that so all the code is
self contained? Maybe it can not always be done, and should you
then have the final code in a block at the end, or do you note
clearly in the text that *this* block is an example, but *this
new* code block is complete and will work? It would be verbose if
you in every instance would quote boilerplate like the import
std.* and so on. I'm not sure I know how to best do it. Teaching
is hard.
More information about the Digitalmars-d-learn
mailing list