如果在编译时间评估该函数和运行时异常,则该如何给出编译错误?
如果我具有可以在运行时提高异常的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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论