3 ms·
C++17 example, showing polymorphism at compile time without macros. Naturally checking for speak() existence with enable_if, static_assert and type traits coul
by pjmlp 2y ago
C++17 example, showing polymorphism at compile time without macros.
Naturally checking for speak() existence with enable_if, static_assert and type traits could be added, though this is an example, and nowdays we would make use of concepts anyway.
#include <iostream>
using namespace std;
class Duck {
public:
void speak() const {
cout << "quack";
}
};
class Dog {
public:
void speak() const {
cout << "auau";
}
};
class Cat {
public:
void speak() const {
cout << "miau";
}
};
template<typename T>
void speaking_animal(const T& animal) {
animal.speak();
cout << "\n\n";
}
template<typename... T>
void speaking_farm(const T&... animals) {
auto space_adder = [&](auto creature) -> void {
creature.speak();
cout << " ";
};
(space_adder(animals), ...);
}
int main() {
Duck duck;
Dog dog;
Cat cat;
speaking_animal(duck);
speaking_animal(dog);
speaking_animal(cat);
speaking_farm(duck, dog, cat);
}
Available at https://godbolt.org/z/WWfx5jWfM https://godbolt.org/z/WWfx5jWfM