简体   繁体   English

如何缩短声明命名常量的时间?

[英]How to shorten declaring named constants?

So if I had to declare multiple constants of the same type like the example below, is there a way to increase efficiency while cutting down the length of the code?那么如果我必须像下面的例子一样声明多个相同类型的常量,有没有办法在减少代码长度的同时提高效率? This is for C++.这是针对 C++ 的。

const double DISCOUNT = .2;

const double CUT_OFF = 150;

const double SHIP_CHARGE = 8.5;

const double TAX_RATE = 0.0825;

Well, you can write it like the following, but really there's no reason to:好吧,你可以像下面这样写,但真的没有理由:

const double DISCOUNT = .2, CUT_OFF = 150, SHIP_CHARGE = 8.5, TAX_RATE = 0.0825;

It's debatable whether it's more readable or not.它是否更具可读性是有争议的。 I personally don't recommend it, and the C++ Core Guidelines don't recommend it either .我个人不推荐它, C++ Core Guidelines 也不推荐它

As a side note, you should be using constexpr instead of const for things like this.附带说明一下,对于这样的事情,您应该使用constexpr而不是const

Well,好,

#define A(b, c) const double b = c;
A(DISCOUNT, .2)
A(CUT_OFF, 150)
A(SHIP_CHARGE, 8.5)
A(TAX_RATE, .0825)

has fewer characters.字符较少。 But it's very hard to read indeed.但确实很难读。 From C++11 onwards prefer constexpr to const .从 C++11 开始,更喜欢constexpr const

"Golfing" C++ code is never to be recommended.永远不推荐“打高尔夫球”C++ 代码。 Write clear code.编写清晰的代码。

Well, this is the way I would do it...嗯,这就是我要做的方式......

Instead ot T you my use something else.而不是你我用别的东西。

using T = const double;

T DISCOUNT = .2;
T CUT_OFF = 150;
T SHIP_CHARGE = 8.5;
T TAX_RATE = 0.0825;

I also would use constexpr but in this case const is the same.我也会使用constexpr但在这种情况下const是相同的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM