Manual distinction of types when given any type T
suggest changeWhen implementing SFINAE using std::enable_if, it is often useful to have access to helper templates that determine whether a given type T matches a set of criteria.
The standard already provides two types analogous to true and false: std::true_type and std::false_type.
The following example shows how to detect whether a type T is a pointer. The is_pointer template mimics std::is_pointer:
template <typename T>
struct is_pointer_: std::false_type {};
template <typename T>
struct is_pointer_<T*>: std::true_type {};
template <typename T>
struct is_pointer: is_pointer_<typename std::remove_cv<T>::type> { };
There are three steps in the above code (sometimes you only need two):
- The first declaration of
is_pointer_is the default case, and inherits fromstd::false_type. The default case should always inherit fromstd::false_typesince it is analogous to a “falsecondition”. - The second declaration specializes
is_pointer_forT*, for anyT. This version inherits fromstd::true_type. - The third declaration removes top-level
constandvolatilefromT, then selects one of the two previous declarations.remove_cvdoes not remove a reference, and it does not stripconstfrom the type a pointer points to.
Since is_pointer<T> is a class, to access its value you need to either:
- Use
::value, e.g.is_pointer<int>::value–valueis a static class member of typeboolinherited fromstd::true_typeorstd::false_type; - Construct an object of this type, e.g.
is_pointer<int>{}. This works becauseis_pointerinherits aconstexprconstructor fromstd::true_typeorstd::false_type, and both of those types have aconstexprconversion tobool.
A variable template (C++14) can expose the value directly:
template <typename T>
constexpr bool is_pointer_v = is_pointer<T>::value;
In C++17 and above, most standard type traits already provide a _v version, such as std::is_pointer_v and std::is_reference_v.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents