Last active
June 5, 2021 20:40
-
-
Save vladiant/9204c0552916be10ba71ad26f4dde76f to your computer and use it in GitHub Desktop.
visit.example.cpp
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
// https://www.youtube.com/watch?v=KRUnZa9OBAM | |
// Generic Programming Without (Writing Your Own) Templates - Tina Ulbrich [ ACCU 2021 ] | |
#include <cmath> | |
#include <iostream> | |
#include <utility> | |
#include <variant> | |
using roots = std::variant<std::pair<double, double>, double, std::monostate>; | |
roots calculate_roots(const double a, const double b, const double c) { | |
const auto d = b * b - 4 * a * c; | |
if (d > 0.0) { | |
const auto p = std::sqrt(d) / (2 * a); | |
return std::pair{-b + p, -b - p}; | |
} | |
if (d == 0.0) { | |
return -b / (2 * a); | |
} | |
return std::monostate(); | |
} | |
template <class... Ts> | |
struct overload : Ts... { | |
using Ts::operator()...; | |
}; | |
template <class... Ts> | |
overload(Ts...) -> overload<Ts...>; | |
int main() { | |
std::visit( | |
overload{[](const std::pair<double, double>& arg) { | |
std::cout << "2 roots " << arg.first << " " << arg.second | |
<< '\n'; | |
}, | |
[](const double& arg) { std::cout << "1 root " << arg << '\n'; }, | |
[](const std::monostate) { std::cout << "no roots found\n"; }}, | |
calculate_roots(10, -2.0, -5.0)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment