Skip to content

Instantly share code, notes, and snippets.

@junaire
Created October 19, 2021 04:56
Show Gist options
  • Save junaire/d5bcce38659553a53b1aed68db4539ef to your computer and use it in GitHub Desktop.
Save junaire/d5bcce38659553a53b1aed68db4539ef to your computer and use it in GitHub Desktop.
Static polymorphism with c++20 concepts
// Core C++ 2021 :: C++ 20 Overview: The Big Four
// https://youtu.be/emcC_Cv8EpQ
#include <iostream>
#include <tuple>
template <typename T>
concept Drawable = requires(T s) {
s.draw();
};
class Rectangle {
public:
auto draw() const { std::cout << "Draw an rectangle!\n"; }
};
class Circle {
public:
auto draw() const { std::cout << "Draw a circle!\n"; }
};
class Square {
public:
auto draw() const { std::cout << "Draw a square!\n"; }
};
template <size_t Index = 0, Drawable... Ts>
constexpr auto drawAll(const std::tuple<Ts...>& shapes) {
if constexpr (Index != sizeof...(Ts)) {
std::get<Index>(shapes).draw();
drawAll<Index + 1>(shapes);
}
}
int main() {
drawAll(std::make_tuple(Rectangle{}, Circle{}, Square{}));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment