如果在编译时间评估该函数和运行时异常,则该如何给出编译错误?

发布于 2025-01-20 20:42:12 字数 702 浏览 1 评论 0原文

如果我具有可以在运行时提高异常的constexPR函数,则如果在编译时对其进行评估,我希望能够给出编译错误。

#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.");
        }
    }
}

我尝试将static_assert放入if语句中,但是无论if语句如何,它都会对其进行评估(因为我假设的IF不是constexpr)。我还尝试了static_assert(x!= 0);,但是它告诉我静态断言的非恒定条件(这有意义...?)。

有没有(最好简单)这样做的方法?谢谢。

编辑:我概括了功能,在我的情况下,我有一个构造函数,我需要使用它来生成编译时间和运行时间对象。因此,如果我尝试创建一个以x为0的constexpr对象,则我希望该程序在x之类的消息中给出编译错误。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文