...

/

Compile-Time Polymorphism and Code Bloat

Compile-Time Polymorphism and Code Bloat

Let’s look at compile-time polymorphism and code bloat.

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:

Press + to interact
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 ...