enable_if is (mostly) obsolete

Since C++ 20 and introduction of concepts, enable_if is obsolete, since concepts can do everything enable_if can, but better.

Concepts allow us to explicitly define constraints for function templates. This makes the code more readable for both developers and compilers.

Why enable_if is not great:

  • it works by using SFINAE to discard function template specializations during overload resolution. This leads to code that is not intuitive and models concepts with template trickery.
  • SFINAE errors are silent, and this leads to some hard-to-debug moments, or for issues to go unnoticed.
  • Even when SFINAE errors happen and we find out about it, there are no clear error messages explaining why they happened.

Why concepts are great:

  • Compilers will report errors on template instantiation
  • Improved compilation times, as compilers prune non-viable function templates early.
  • They are nicer to write, and require much less cryptic typing

TLDR: Use concepts, don’t use enable_if.

Leave a Reply

Your email address will not be published. Required fields are marked *