温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

C++怎么定义constexpr

发布时间:2021-11-25 15:38:24 来源:亿速云 阅读:114 作者:iii 栏目:大数据

这篇文章主要介绍“C++怎么定义constexpr”,在日常操作中,相信很多人在C++怎么定义constexpr问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”C++怎么定义constexpr”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

如果函数有可能需要编译时计算,将它定义为constexpr

Reason(原因)

constexpr is needed to tell the compiler to allow compile-time evaluation.

希望告诉编译器允许编译时计算的时候需要使用constexpr。

Example(示例)

The (in)famous factorial:

以下是(非)著名的阶乘算法:

constexpr int fac(int n){    constexpr int max_exp = 17;      // constexpr enables max_exp to be used in Expects    Expects(0 <= n && n < max_exp);  // prevent silliness and overflow    int x = 1;    for (int i = 2; i <= n; ++i) x *= i;    return x;}

This is C++14. For C++11, use a recursive formulation of fac().

这是C++14中的做法。对于C++11,使用递归形式的fac()。

Note(注意)

常数表达式不会保证编译时计算;它只是表示如果函数的参数为常数表达式,而且程序员希望或者编译器判断这么做的情况下可以在编译时计算。

constexpr int min(int x, int y) { return x < y ? x : y; }
void test(int v){    int m1 = min(-1, 2);            // probably compile-time evaluation    constexpr int m2 = min(-1, 2);  // compile-time evaluation    int m3 = min(-1, v);            // run-time evaluation    constexpr int m4 = min(-1, v);  // error: cannot evaluate at compile time}  
Note(注意)

Don't try to make all functions constexpr. Most computation is best done at run time.

不要试图将所有的函数指定为constexpr。大部分计算更适合在执行时进行。

Note(注意)

任何最终依靠高层次实时配置或者商业逻辑的API都不应该被指定为constexpr。这样的定制无法在编译时进行,依赖这个API的任何constexpr函数必须重构或者去掉constexpr属性。

Enforcement(实施建议)

Impossible and unnecessary. The compiler gives an error if a non-constexpr function is called where a constant is required.

不可能也不必要。如果需要一个常量结果而非constexpr函数被调用的话,编译器会报错。

到此,关于“C++怎么定义constexpr”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

c++
AI