Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

R3.2.8 “不应使用宏定义常量” 中的正确示例可以改进 #49

Open
Mq-b opened this issue Feb 2, 2024 · 1 comment
Open

Comments

@Mq-b
Copy link
Contributor

Mq-b commented Feb 2, 2024

原文:

应改为:

namespace U {
   const float PI = 3.14F;  // Compliant
}

namespace V {
   const long double PI = 3.14159L;  // Compliant
}

const 替换为 constexpr 会更加合适。

主要是有几点考量:

  1. const 修饰的标量类型可以进行非常量初始化,

    int a = 1;
    const int n = a;
  2. const 修饰的标量类型,不一定是“常量表达式”,

    template<int a>
    int i_v{};
    
    const int i = 1; // 常量表达式初始化
    int b = 1;
    const int i2 = b;
    
    i_v<i>;         // i  是整形常量表达式 OK
    i_v<i2>;        // i2 不是整形常量表达式 Error

    如果更换为 constexpr 则没有这些问题了。

  3. 由于关键字复用和 C 语言的缘故,const 本身的含义不那么明确,它的要求也不是那么严格,如果确定是常量,在 C++ 中应该使用 constexpr

    原文使用了命名空间,默认 C++ 的语境。

@brotherbeer
Copy link
Collaborator

好主意~

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants