C/C++ Arena

Step 5 of 8

if constexpr

Inside a template, if constexpr picks a branch at compile time, and the other branch isn't even compiled for that type. Combine it with type traits from <type_traits>:

template <typename T>
std::string kind(const T&) {
    if constexpr (std::is_integral_v<T>) return "integer";
    else if constexpr (std::is_floating_point_v<T>) return "float";
    else return "other";
}

Your turn: write template <typename T> std::string to_text(const T& v): for arithmetic types (std::is_arithmetic_v<T>) return std::to_string(v), and otherwise assume it's already a string and return "\"" + v + "\"" (quoted).

Previous: constexpr Next: Values as template parameters