Created
October 19, 2021 04:56
-
-
Save junaire/d5bcce38659553a53b1aed68db4539ef to your computer and use it in GitHub Desktop.
Static polymorphism with c++20 concepts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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