Roger Orr gave this month’s ACCU presentation on Making Templates Easier in C++. He showed two techniques that people commonly use to tailor template implementations for specific types: Tag Dispatch and SFINAE (via enable_if).
With Tag Dispatch, you can switch to different implementations of a template function using traits classes based on one of the input parameter types (e.g. use std::iterator_traits to target a faster implementation for random access iterators). The downside is that you often have to duplicate code across the different implementations.
With SFINAE, you can use typedefs within a parameter type to disable particular overloads. E.g. STL containers have a ::value_type typedef, so you can use that to differentiate between collections and scalar inputs. The downside is that you sometimes have to add additional, defaulted template parameters to allow the compiler to distinguish between otherwise identical template definitions.
Roger then introduced
constexpr if from C++17 and concepts from C++20.
The advantages of
constexpr if are that it can be used both inside and outside templates and specialisations can be defined inline. Any code that would not compile can be put inside a
constexpr if and will be discarded. This seems more straightforward than the recursive template solutions Roger showed earlier in the talk.
Concepts are intended to help define the requirements of a template in a way visible to the compiler as well as the developer. Reusing concept definitions should leave to a domain-specific language that helps within a project. Better still, use of a template parameter type that doesn’t satisfy concept requirements will generate a more helpful error message than if SFINAE were used to achieve the constraints.
The finale was an overview of the new SpaceShip operator, !
The video is now available on the SkillsMatter website.