首页 文章详情

C++核心准则边译边学-F.4 如果函数有可能需要编译时计算,将它定义...

面向对象思考 | 812 2019-11-03 23:27 0 0 0
UniSMS (合一短信)

d3345ca6d691be128a19730fbe25108e.webp

F.4: If a function may have to be evaluated at compile time, declare it constexpr(如果函数有可能需要编译时计算,将它定义为constexpr)


关于constexpr的基础知识,可以参照以下链接:

https://mp.weixin.qq.com/s/Y_pEIVO8H6u-fpPczJU5Mw

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 does not guarantee compile-time evaluation; it just guarantees that the function can be evaluated at compile time for constant expression arguments if the programmer requires it or the compiler decides to do so to optimize.

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

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(注意)

Any API that may eventually depend on high-level run-time configuration or business logic should not be made constexpr. Such customization can not be evaluated by the compiler, and any constexpr functions that depended upon that API would have to be refactored or drop constexpr.

任何最终依靠高层次实时配置或者商业逻辑的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函数被调用的话,编译器会报错。


good-icon 0
favorite-icon 0
收藏
回复数量: 0
    暂无评论~~
    Ctrl+Enter