C ++-Static_assert和constexpr函数在运行时求值的能力 [英] C++ - Static_assert and ability of constexpr functions to evaluate at runtime

查看:100
本文介绍了C ++-Static_assert和constexpr函数在运行时求值的能力的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读有关C ++中的 constexpr static_assert 功能的信息,似乎让我感到困惑-我您已经读到 constexpr 函数不一定在编译期间就进行评估,它们有时可以在运行时进行评估。让我困扰的一件事是,在编译过程中总是检查 static_assert 。那么,如果我们将 constexpr 传递给 static_assert ,但是编译器选择评估该 constexpr,会发生什么情况? 在运行时?

I'm reading about constexpr and static_assert features in C++ and one thing seems confusing to me - I've read that constexpr functions are not necessarily always evaluated during compilation and they can sometimes evaluate at runtime. One thing that bothers me is that static_assert is always checked during compilation. So what happens, if we pass constexpr to static_assert, but compiler chooses to evaluate that constexpr during runtime? Is that even an issue?

推荐答案


constexpr函数不一定在编译过程中会评估

constexpr functions are not necessarily always evaluated during compilation

总是在编译时对它进行评估,因此将其返回值用作const表达式时。

It is always evaluated at compile time when it should be, so when its return value is used as const expression.

static_assert 是这种情况之一。
constexpr int值= f(); C< f()> c; (模板参数)是其他情况。

static_assert is one of this case. constexpr int value = f(); or C<f()> c;(template argument) are other cases.

但在 std :: cout<<中f(),不需要在编译时进行计算。

but in std::cout << f(), it is not required to be computed at compile time.

并且在 void bar(int p ){const int v = f(p);} f 不能被评估为 constexpr (取决于(不是) constexpr 的函数参数)。

And in void bar(int p) { const int v = f(p);}, f cannot be evaluated as constexpr (depend of parameter of function which are not (cannot be) constexpr).

这篇关于C ++-Static_assert和constexpr函数在运行时求值的能力的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆