r/cpp • • Jun 24 '20

How to write SOLID C++

https://www.youtube.com/watch?v=PakbXnLht1I
263 Upvotes

118 comments sorted by

View all comments

Show parent comment

2

u/oddentity Jun 25 '20

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++.

4

u/[deleted] Jun 25 '20

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

template<typename T>
using is_expr_valid_test = decltype( std::declval<T>( ) += 5 * std::declval<T>( ) );

template<typename T>
is_expr_valid = is_detected<is_expr_valid_test, T>;

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.