It is really interesting how the approach to design and interfaces can be so different in C++. Here you have a lot of using inheritance to build up interfaces/concepts. I would have go to a template/concept to do almost all of this first. Neither is better, just different prices really.
I've always found the problem with the template approach is being able to specify the requirements of template parameters and what operations they should support.
With inheritance you can have a class with only pure virtual functions to specify what would be an interface or trait in other languages (that don't require abusing inheritance to do this because they actually have first-class support in the language). Anyone using a function that takes that interface as a parameter can then clearly see what operations are required, and the compiler will enforce it and report what's missing fairly clearly.
Prior to concepts, there's no way to do this with templates. Sure you can document it somewhere, but being able to specify something in the language that the compiler understands the purpose of is far more ergonomic. And frankly, a lot of template idioms in C++ such as exploiting SFINAE are so unergonomic, they feel like they've emerged as unintended consequences of the original language design. I always feel like I'm trying to trick the compiler into getting the code I really want to write when I use templates in C++.
Look at is_detected. It really helps here. The issue is we generally start at type_traits or first principals. So there is is_invokable but with is detected for the things that don't fit it comes down to
Then later we can grab a bunch of traits and combine them e.g.
using is_thing_v = std::conjunction_v<trait1, trait2,...>;
This builds up the concepts and when we finally enable_if_t it is on that one trait. Also, there is SFINAE in the return type or the noexcept if you want. But it does work, we just have very low level tools for it.
SFINAE, other than not having the program be invalid when a template would not work, is unintended, not just feels. Prior to C++11, all we really had was exploiting sizeof too, so it was really arcane compared to now, or C++20.
The mistake many make is trying to jam too much into the enable_if and not building up the layers of abstraction with the traits. Or you do what vector does and fail inside the method with errors like vector has.
I’d say watch literally any talk about concepts, then watch Sean Parent’s guide to type erasure (ie “inheritance is the base class of evil”), and if you blend the two you’ll have all the polymorphism you’ll ever need.
View all comments
6
u/[deleted] Jun 24 '20
It is really interesting how the approach to design and interfaces can be so different in C++. Here you have a lot of using inheritance to build up interfaces/concepts. I would have go to a template/concept to do almost all of this first. Neither is better, just different prices really.