D templated interface idiom

If you are not familiar with the Non Virtual Interface idiom I recommend that you go and read about it. D takes this idiom to the next level by allowing to have tempalted methods within interfaces if they are final. This can be very powerfull and help reducing boilerplate code.

If you look at the above example you can see that the IInputStream interface has two templated methods which are final. Thos methods implement the behavior needed for arrays and value types. Then they forward the read in the correct way to readImpl. As a result implementing the IInputStream interface becomes really easy. The only method that needs to be implemented is the readImpl method as you see from the FileInStream class. The correct handling of different types only has to be implemented once, inside the interface, and all implementations don’t have to care about this anymore. You could also think of something similar for serializing data. A ISerializer interface which implementes all the needed type handling as templates and forwards it to simple protected methods. Then implementing different serialization targets (e.g. json, xml, binary, etc) would be quite easy and not require writing and testing template code anymore. A further advantage of this idiom is, that it lowers the amout of code bloat because the templates only get generated once for the interface and are reused by every implementation.

The above code was tested with dmd 2.063.2