Tutorial by Examples

std::enable_if is a convenient utility to use boolean conditions to trigger SFINAE. It is defined as: template <bool Cond, typename Result=void> struct enable_if { }; template <typename Result> struct enable_if<true, Result> { using type = Result; }; That is, enable_...
C++11 void_t is a meta-function that maps any (number of) types to type void. The primary purpose of void_t is to facilitate writing of type traits. std::void_t will be part of C++17, but until then, it is extremely straightforward to implement: template <class...> using void_t = void; ...
C++11 One of constraining function is to use trailing decltype to specify the return type: namespace details { using std::to_string; // this one is constrained on being able to call to_string(T) template <class T> auto convert_to_string(T const& val, int ) ->...
SFINAE stands for Substitution Failure Is Not An Error. Ill-formed code that results from substituting types (or values) to instantiate a function template or a class template is not a hard compile error, it is only treated as a deduction failure. Deduction failures on instantiating function templa...
C++11 Motivational example When you have a variadic template pack in the template parameters list, like in the following code snippet: template<typename ...Args> void func(Args &&...args) { //... }; The standard library (prior to C++17) offers no direct way to write enable_if...
To generalize type_trait creation:based on SFINAE there are experimental traits detected_or, detected_t, is_detected. With template parameters typename Default, template <typename...> Op and typename ... Args: is_detected: alias of std::true_type or std::false_type depending of the validi...
If you need to select between several options, enabling just one via enable_if<> can be quite cumbersome, since several conditions needs to be negated too. The ordering between overloads can instead be selected using inheritance, i.e. tag dispatch. Instead of testing for the thing that ne...

Page 1 of 1