4 ms·
I found the use of 'if constexpr' in the example pretty nasty. I would have thought it more idiomatic to use std::enable_if to enable different implementations
by RossBencina 7y ago
I found the use of 'if constexpr' in the example pretty nasty. I would have thought it more idiomatic to use std::enable_if to enable different implementations of 'algorithm' as in the example of 'construct' and 'destroy' given here:
https://en.cppreference.com/w/cpp/types/enable_if https://en.cppreference.com/w/cpp/types/enable_if
- jcelerier 7y ago> I found the use of 'if constexpr' in the example pretty nasty. For new code it is to be preferred - it generates less symbols than enable_if, compiles faster (by a noticeable margin from my own experience) and makes for more readable code as you don't have to go look everywhere for the various enable_if cases.
- gpderetta 7y agoEnable if is fine if you have mutually exclusive choices (although the way it work is pure magic), but it quickly becomes very complex for overlapping cases as you have to somehow hack the partial ordering in. A chain of constexpr if is significantly easier to write and understand. The right solution are of course concepts.
- skrebbel 7y agoMost of this is pretty new to me. Why is it nasty? It looks neat to me!
- RossBencina 7y agoI consider it nasty (compared to the std::enable_if example that I linked) because it does not express the programmer's intent. When you use enable_if to enable specific algorithm variants for specific trait predicates, you're saying "here is the specialised algorithm to use when this predicate is satisfied". Both the predicate and the algorithm code that relies on the predicate being satisfied are part of the template specialization definition. There's no chance of missing a precondition: it's stated right in the definition. Another advantage is that it's completely modular -- you can add or remove specializations at will. On the other hand, the example in the post using 'if constexpr' wraps the algorithm in an extra layer of indirection (a generic wrapper) with a bunch of constexpr if-else spaghetti used to dispatch to the correct implementation. Even if the if-else spaghetti is pristine, the fact remains that the predicate and the specialized code that depends on the predicate as a precondition have been separated out into two independent code sites.