Conditionally compiling classes and functions with enable_if
Template metaprogramming is a powerful feature of C++ that enables us to write generic classes and functions that work with any type. That is actually a problem sometimes because the language does not define any mechanism for specifying constraints on the types that can be substituted for the template parameters. However, we can still achieve that using metaprogramming tricks and leveraging a rule called substitution failure is not an error, known shortly as SFINAE. This recipe will focus on implementing type constraints for templates.
Getting ready
Developers have used a class template usually called enable_if
for many years in conjunction with SFINAE to implement constraints on template types. The enable_if
family of templates has become part of the C++11 standard and is implemented as follows:
template<bool Test, class T = void> struct enable_if {}; template<class T> struct enable_if<true...