Template class with dispatched properties
Chris Cain
clcain at uncg.edu
Thu Nov 7 22:53:34 PST 2013
On Friday, 8 November 2013 at 05:10:57 UTC, Ross Hays wrote:
> Okay here is something I was hoping for some general
> clarification on related to this and maybe you can help me sort
> some things out.
>
> The opDispatch method has a template parameter of string
> fieldName. In C++, templates are actually compiled so each
> different use of a template class is compiled into its own
> thing. With D, if this is the case I imagine I would not be
> able to access the template parameter of string? If I can then
> why does it need to be a template parameter at all and not a
> normal parameter.
Yes, D is the same as C++ in that each unique template
instantiation is compiled differently. Almost like copy & paste
where you replace the template parameters with what was passed in.
What do you mean by "not be able to access the template parameter
of string"? If you just mean whether you can use it or not, well,
you can. It's available to you both at compile time and at run
time if it's a template parameter like that. In the case of
opDispatch, the compiler essentially rewrites all unknown calls
(if `x.foo()` doesn't exist, then change it to
`x.opDispatch!"foo"()`). One of the reasons why passing it in as
a template parameter is better than a regular parameter is that
opDispatch!s can specialize at compile time so that it doesn't
result in any runtime performance hit.
You can look at it like this: with a compile-time opDispatch
means that `opDispatch!"x"; opDispatch!"y";` and so on is
(essentially) binary equivalent to you having actually
hand-written those functions (that is just a hand-written `x` or
`y` property). So, there's no runtime overhead of conditionals,
no allocating strings, no actual passing of parameters, or,
potentially, even the creation of that offset variable (so, it
doesn't even do the subtraction at runtime because it can figure
it out at compile time and just fill it in as if it were a
literal).
One tiny place of improvement for your code, however, is if you
changed it to `static immutable offset = ...;` because that helps
the compiler know to do that operation at compile time. That
said, a Sufficiently Smart Compiler (tm) would be able to do it
regardless of the extra hint, but AFAIK DMD typically doesn't do
all of the optimizations it could.
More information about the Digitalmars-d-learn
mailing list