千家信息网

C++怎么定义constexpr

发表于:2024-10-22 作者:千家信息网编辑
千家信息网最后更新 2024年10月22日,这篇文章主要介绍"C++怎么定义constexpr",在日常操作中,相信很多人在C++怎么定义constexpr问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答"C++怎么
千家信息网最后更新 2024年10月22日C++怎么定义constexpr

这篇文章主要介绍"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"的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注网站,小编会继续努力为大家带来更多实用的文章!

0