On Friday, 7 April 2017 at 13:30:00 UTC, Marco Leise wrote:
[...]


Thank you Marco, you have summarized the issues of both worlds.

I guess that's why java' implementation is different, templates in java are synonymous to classes. But that relies on virtualization, and is too restrictive, no primitive types allowed, no structs (java has no structs), and no structural subtyping (the object has to implement the interface).

Still I think there has to be a better way to implement templates.
as far as speed goes the current implementation is hard to beat, since every thing is flat, there's no overhead.

To add to the current implementations I think one way to implement templates or more generally structural subtyping (aka duck typing) would be, to pass metadata (offsets of functions and fields) to functions, the same way you would pass function arguments i.e in a defined order and signature. Every function would declare the metadata it requires for each argument passed i.e which field and function it uses on that object, i.e there's an extra signature (the compiler could take care of that).

Pros:
- static duck-typing (awesome).
- enables binary distribution since one instance suffices.
- faster than virtualization, it has less overhead with always only one indirection, to call a function fetch it from the argument list then call it. - replaces virtualization, inheritance could be implemented on top of this. - does not change the syntax of the language, only the compiler needs to worry about the extra signature introduced therefore it can be distributed as header files generated by the compiler.

Cons:
- introduces a extra signature.
- slower than the current implementation of templates, there is still an indirection (a pointer dereference is not an immediate value). - the extra signature requires extra effort to keep ABI compatibility, which is an undesirable side effect, if the implementation of an algorithm changes it can't use different fields or functions without breaking the ABI.
- uses more space on the stack and cpu cache.
- more work for the compiler to infer the used fields and fuctions
- has some issues

Issues:
- static method calls and normal method calls are ambigious i.e functions and delegates. - to add to that even fields get into the mess, in `a.b`, b could be a field or a method or a static field or a static method. - conditional compilation notably used in design by introspection can't be worked at runtime. but since conditional compilation is predictable unlike generic programing, maybe all possible branches could be compiled into the binary and the compiler could just link to one of them.

This is just one other way to consider maybe there more, there always is, we just need to think outside the box (sometimes recursively).

Reply via email to