Home > Software engineering >  can you replace enable_if to disable a function it if constexpr?
can you replace enable_if to disable a function it if constexpr?

Time:10-15

So I know you can use enable_if to disable a function template (e.g. if the type is not integral) - but can you do the same with constexpr?

i.e. is there an equivalent for this:

template<class T, typename = std::enable_if_t<std::is_integral_v<T>> >
T test2()
{
    return {};
}

with constexpr - something like:

template <typename T>
T test()
{
    // we expect various integral and floating point types here
    if constexpr (std::is_integral_v<T>)
    {
        T output{};
        return output;
    }
    else
    {
       // trigger compiler error
       return{};
    }
}

so I want:

test(1); // compile ok
test(std::string("hello")); // compile fail

CodePudding user response:

It is as simple as this:

template <typename T>
T test()
{
  static_assert(std::is_integral_v<T>);
  T output{};
  return output;
}

CodePudding user response:

You can use static_assert with a type-dependent expression that is always false in constexpr if.

template<class> inline constexpr bool dependent_false_v = false;
template <> inline constexpr bool dependent_false_v<decltype([](){})> = true; // requires C  20
template <typename T>
T test(T)
{
    // we expect various integral and floating point types here
    if constexpr (std::is_integral_v<T> || std::is_floating_point_v<T>)
    {
        T output{};
        return output;
    }
    else
    {
       // trigger compiler error
       static_assert(dependent_false_v<T>);
    }
}
  • Related