【C++ TMP】The void_t idiom


Since C++ 17, we can use the variadic template class std::void_t to implement class specialization. Typically, it is used to detect whether a type supports some map of type.

Example: remove_all_extents for array-like types

#include 
#include 

template 
struct remove_all_extents {
  typedef std::remove_reference_t type;
};

template 
struct remove_all_extents()[0])>> {
    typedef typename remove_all_extents()[0])>::type type;
};

#include 
#include 

int main() {
    std::cout << std::boolalpha;
    std::cout << std::is_same_v::type, int> << "\n";    
    std::cout << std::is_same_v::type, double> << "\n";
    std::cout << std::is_same_v>::type, int> << "\n"; 
    using v2 = std::vector>;   
    std::cout << std::is_same_v::type,int> << "\n";
}

https://godbolt.org/z/hvG3chYfx

std::void_t is used here to detect whether the given type T supports the subscript operator.

References

https://en.cppreference.com/w/cpp/types/void_t