Skip to content

Instantly share code, notes, and snippets.

@vladiant
Last active June 5, 2021 20:40
Show Gist options
  • Save vladiant/9204c0552916be10ba71ad26f4dde76f to your computer and use it in GitHub Desktop.
Save vladiant/9204c0552916be10ba71ad26f4dde76f to your computer and use it in GitHub Desktop.
visit.example.cpp
// 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