Compile Time Type Determination

We could decide whether we should execute or enable a section of codes based on circumstances. C++ standard libraries provides various ways to support this prior to C++20. In C++20, there is no need for it because of 202203281200#.

enable_if (C++11 and later)

To use enable_if, import it from the library <type_traits>. It is useful especially when dealing with classes where in some cases there is no general need of a function except for a particular type. The following shows such example:

template<typename T>
class Smart_pointer {
  // ...
  T& operator*();
  std::enable_if<is_class<T>(), T&> operator->();
}

The * operator could be used for variety of types without restriction. However, in order to use the operator ->, the type T has to be a class, specified from the #type predicate is_class.

As you can see, the first template parameter of enable_if is the type predicate, and the second template parameter will be the return type of the function. Thus, the statement will be parsed as T& operator->() if and only if T is a class.

Compile-Time if (C++17 and later)

When there is a need to execute a section of codes only when the type has met #some characteristics, compile-time if could be in great use. See the following examples:

template<typename T>
void update(T& target)
{
  // ...
  if constexpr (is_pod<T>::value) { // is_pod is from <type_traits>
    simple_and_fast(target);
  } else {
    slow_and_safe(target);
  }
  // ...
}

If T is of pod type, that is of plain old data type, then the function update will run the function simple_and_fast on the target variable. Otherwise, it will run the function slow_and_safe.

Links to this page
  • C++ Traits

    C++ standard libraries contains type_traits and iterator_traits defined in the libraries <type_traits> and <iterator> respectively. They are used heavily in 202204181536# and 202204182011# but soon deem unnecessary due to the introduction of #202203281200 in C++20.

  • C++ Container

    Standard libraries’ containers usually define value_type and iterator to indicate what type of the value and iterator are stored or used in them. It is advised to follow this convention if a custom container should be used. This could be useful if 202204181536 should be used in the codebase although in C++20, 202203281200 is the better alternative for it.

  • C++ Concepts

    C++(20) Concepts has superseded the functionalities from #202204181611, #202204181536 and #202204182011. It could be defined as follows using concept keyword:

#metaprogramming #cpp #type-check