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
.