Skip to content

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

Description

@Mq-b

原文:

应改为:

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++ 的语境。

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions