Search⌘ K
AI Features

With if constexpr

Explore how to use if constexpr in C++17 to create flexible factory methods, replacing the older enable_if approach. Understand how if constexpr allows for cleaner code by evaluating conditions at compile time, improving readability and avoiding unnecessary function overloads. Learn how this modern feature helps manage template metaprogramming with practical examples.

Before C++17

Using enable_if

In the previous solution (pre C++17) std::enable_if had to be used:

C++
template <typename Concrete, typename... Ts>
enable_if_t<is_constructible<Concrete, Ts...>::value, unique_ptr<Concrete>>
constructArgsOld(Ts&&... params)
{
return std::make_unique<Concrete>(forward<Ts>(params)...);
}
template <typename Concrete, typename... Ts>
enable_if_t<!is_constructible<Concrete, Ts...>::value, unique_ptr<Concrete> >
constructArgsOld(...)
{
return nullptr;
}

std::is_constructible - allows us to test if a list of arguments could be used to create a given type.

Just a quick reminder about enable_if ...