Manual distinction of types when given any type T

suggest change

When 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):

  1. The first declaration of is_pointer_ is the default case, and inherits from std::false_type. The default case should always inherit from std::false_type since it is analogous to a “false condition”.
  2. The second declaration specializes is_pointer_ for T*, for any T. This version inherits from std::true_type.
  3. The third declaration removes top-level const and volatile from T, then selects one of the two previous declarations. remove_cv does not remove a reference, and it does not strip const from the type a pointer points to.

Since is_pointer<T> is a class, to access its value you need to either:

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.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents