'How can I give a compile error if the function is evaluated at compile time and a runtime exception otherwise?

If I have a constexpr function that can raise an exception at runtime, I want to make it able to give a compile error if it's evaluated at compile time.

#include <stdexcept>
#include <type_traits>

constexpr void func (const int x)
{
    if (x == 0) {
        if (std::is_constant_evaluated()) {
            /// compile error
        } else {
            throw std::invalid_argument("x cannot be 0.");
        }
    }
}

I have tried putting static_assert inside the if statement, but it evaluates it regardless of the if statement (since the if is not constexpr I'm assuming). I have also tried static_assert(x != 0);, but it tells me non-constant condition for static assertion (which makes some sense...?).

Is there any (preferably easy) way to do this? Thanks.

EDIT: I generalized the function, in my case I have a constructor that I need to use to generate both compile time and run time objects. So I would like the program to give a compile error with a message like x cannot be 0 if I try to create a constexpr object with x being 0.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source