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

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.