Search⌘ K

Compile-Time Polymorphism and Code Bloat

Understand the concept of compile-time polymorphism in D, which enables behavior-based type compatibility using templates. Learn the differences between compile-time and run-time polymorphism, and discover how repeated code generation from templates can lead to code bloat. This lesson helps you evaluate trade-offs between polymorphism approaches and manage program size effectively.

We'll cover the following...

Compile-time polymorphism

In object-oriented programming (OOP), polymorphism is achieved using inheritance. For example, if a function takes an interface as a parameter, it accepts objects of any class that inherits that interface.

Let’s recall an earlier example from a previous chapter:

D
import std.stdio;
interface SoundEmitter {
string emitSound();
}
class Violin : SoundEmitter {
string emitSound() {
return "♩♪♪";
}
}
class Bell : SoundEmitter {
string emitSound() {
return "ding";
}
}
void useSoundEmittingObject(SoundEmitter object) {
// ... some operations ...
writeln(object.emitSound());
// ... more operations ...
}
void main() {
useSoundEmittingObject(new Violin);
useSoundEmittingObject(new Bell);
}

useSoundEmittingObject() benefits from polymorphism. It takes a SoundEmitter so that it can be used with any type that is derived from that interface.

Since working with any type is inherent to templates, they can also be seen as providing a kind of polymorphism. Being a compile-time feature, the polymorphism that templates provide is called ...