Usage example of is_detected and enable_if_t combined

As is_detected::value is a compile-time Boolean, is_detected can be combined with enable_if_t to enable a certain function for classes that contain a particular member function.

For example, we can implement a generic print function that can print both the to_string() method and the name_ member variable, depending on what the printed class has implemented:

namespace exp = std::experimental;template<typename T> using has_to_string = decltype(&T::to_string);template<typename T> using has_name_member = decltype(T::name_);// Print the to_string() function if it exists in classtemplate < typename T, bool HasToString = exp::is_detected<has_to_string,T>::value, bool HasNameMember = exp::is_detected<has_name_member,T>::value ...

Get C++ High Performance now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.