21 ms·
Here's the first example in C++: #include <concepts> #include <iostream> #include <numbers> template<class shape> concept Shape = requ
by scatters 6y ago
Here's the first example in C++:
#include <concepts>
#include <iostream>
#include <numbers>
template<class shape>
concept Shape = requires(
shape s,
shape (&&circle)(double, double, double),
shape (&&rectangle)(double, double, double, double)) {
{ s(circle, rectangle) } -> std::same_as<shape>; };
auto Circle = [](double x, double y, double r) -> Shape auto {
return [=](auto&& circle, auto&& rectangle) { return circle(x, y, r); }; };
auto Rectangle = [](double x, double y, double w, double h) -> Shape auto {
return [=](auto&& circle, auto&& rectangle) { return rectangle(x, y, w, h); }; };
Shape auto exampleCircle = Circle(2.0, 1.4, 4.5);
Shape auto exampleRectangle = Rectangle(1.3, 3.1, 10.3, 7.7);
auto area = [](Shape auto shape) -> double { return shape(
[](auto, auto, auto r) { return std::numbers::pi * r * r; },
[](auto, auto, auto w, auto h) { return w * h; }); };
int main() {
std::cout << area(exampleCircle) << std::endl;
std::cout << area(exampleRectangle) << std::endl;
}
Of course, this is missing type-erasure, which you'd need to pass `Shape` across TU boundaries, but that's unnecessary if you're happy to use parametric polymorphism.
- pjmlp 6y agoWhich could be done with a little help from std::any, just as info for others.
- dfgdghdf 6y agoIs C++ cheating since it has such a powerful type-system? I would like to see an attempt in Java.
- matheusmoreira 6y agoWhoa! C++ has become an almost completely different language since I learned it over 10 years ago...
- jfengel 6y agoThat was precisely what I was going to say. I don't recognize any of that.
- AnimalMuppet 6y agoI, uh, recognized "#include", but not much else...
- scatters 6y agoThat'll be gone soon: https://en.cppreference.com/w/cpp/language/modules https://en.cppreference.com/w/cpp/language/modules
- matheusmoreira 6y agoYeah, I recognize the lambda expressions and not much else. How does the new stuff even interact with the older features? I can't even tell if something is recommended or deprecated anymore. Can you imagine the sheer work of maintaining a compiler for this thing? Really makes me appreciate the relative simplicity of C. On a positive note, it looks like the standard library became amazing. It seems really well designed. Contains things that used to be preprocessor definitions, lots of very popular functionality, good symbol names and no cryptic abbreviations anywhere. Did it absorb some of boost?